为什么在传递对象时使用‘ref’关键字?

如果要将对象传递给方法,为什么要使用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; }}

输出为“Bar”,这意味着将对象作为引用传递。

为什么在传递对象时使用‘ref’关键字?

海绵宝宝撒
浏览 670回答 3
3回答

米脂

您需要区分“按值传递引用”和“通过引用传递参数/参数”。我写了一个关于这一主题的相当长的文章为了避免每次出现在新闻组上时都要小心地写:)
打开App,查看更多内容
随时随地看视频慕课网APP