如果我将对象传递给方法,为什么要使用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",表示该对象作为参考传递.
我一直以为他们是关于同样的事情,但有人在我的一个答案中指出了我并不是这样.
编辑:这是我说的和我得到的评论.Edit2:C++之间的区别是什么:
public: void foo(int& bar);
Run Code Online (Sandbox Code Playgroud)
和C#的
public void foo(ref int bar){
}
Run Code Online (Sandbox Code Playgroud)