【发布时间】:2010-12-08 13:05:24
【问题描述】:
我正在学习(新手).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
}
}
输出:
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!
【问题讨论】:
-
可能值得您花时间reading this article 了解字符串如何表现得很奇怪但实际上很简单,这对我来说无疑是大开眼界!