如果我将对象传递给方法,为什么要使用ref关键字?这不是默认行为吗?
例如:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
输出为"Bar",表示该对象作为参考传递.
这是我的c#代码.为什么引用类型不在C#中更新,下面是代码
class Program
{
public static void Main(string[] args)
{
var a = A.field;
A.field = "2";
Console.WriteLine(a);
Console.Read();
}
}
public static class A
{
public static string field = "1";
}
Run Code Online (Sandbox Code Playgroud)
结果是1,为什么?