我正在学习(新手).NET,我有些疑惑.
从书中读到的例子我了解到String是对象,然后是Reference Type.
所以,我做了这个测试,结果与我的预期不同:
我真的很好奇,这是一个例外,因为"字符串"是特殊类型吗?
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);
} …Run Code Online (Sandbox Code Playgroud) 当引用变量可以通过引用传递时:
class Example
{
public string str="Demo";
public int[] intValues={1,3,4,5};
public static void StrPassing(string someStr)
{
string otherStr="Changed!";
someStr=otherStr;
}
public static void NumPassing(int[] a)
{
a[2] = 115;
}
}
static void Main(string[] args)
{
Example ex = new Example();
Example.StrPassing(ex.str);
Example.NumPassing(ex.intValues);
foreach (int i in ex.intValues)
{
Console.WriteLine(i);
}
Console.WriteLine(ex.str);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
值intValues[2]被改变115为参考正在passed.But(演示)的字符串"海峡"的值不会更改为"改变了!"这是什么原因呢?我.可把它作为数组传递通过引用和其他引用类型按值传递?