我一直在学习(新手).NET,但我有一些疑问。
从书中的例子中我了解到,字符串是对象,然后是引用类型。
所以,我做了这个测试,结果与我预期的不同:
我真的很好奇,这是一个例外吗,因为“字符串”是特殊类型?
class Program
{
static void Main(string[] args)
{
SByte a = 0;
Byte b = 0;
Int16 c = 0;
Int32 d = 0;
Int64 e = 0;
string s = "";
Exception ex = new Exception();
object[] types = { a, b, c, d, e, s, ex };
// C#
foreach (object o in types)
{
string type;
if (o.GetType().IsValueType)
type = "Value type";
else
type = "Reference Type";
Console.WriteLine("{0}: {1}", o.GetType(), type);
}
// Test if change
string str = "I'll never will change!";
Program.changeMe(str);
Console.WriteLine(str);
}
public static string changeMe(string param)
{
param = "I have changed you!!!";
return ""; // no return for test
}
}
Output:
System.SByte: Value type
System.Byte: Value type
System.Int16: Value type
System.Int32: Value type
System.Int64: Value type
System.String: Reference Type
System.Exception: Reference Type
I'll never will change!
String确实是一个引用类型。但是,当您的 Main 方法调用changeMe(str) 时,.NET 会将对 str 的引用的副本传递给 param 参数中的changeMe。然后,changeMe 修改此副本以引用“我改变了你!!!”,但原始 str 引用仍然指向“我永远不会改变”。
作为引用类型意味着如果您更改了state对于传递的字符串,调用者将看到这些更改。 (您不能对字符串执行此操作,因为字符串是不可变的,但您可以对其他引用类型执行此操作,例如 Control。)但是重新分配参数不会更改value调用者传入该参数,即使该值是引用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)