【问题标题】:"ref" keyword and reference types [duplicate]“ref”关键字和引用类型[重复]
【发布时间】:2023-03-28 04:47:01
【问题描述】:

我团队中的某个人偶然发现了 ref 关键字在引用类型上的特殊用法

class A { /* ... */ } 

class B
{    
    public void DoSomething(ref A myObject)
    {
       // ...
    }
}

有任何理智的人会做这种事的理由吗?我在 C# 中找不到它的用途

【问题讨论】:

  • 另见this question
  • 确实,我在搜索时错过了这个问题。好收获

标签: c# .net pass-by-reference ref reference-type


【解决方案1】:

仅当他们想要将作为myObject 传入的对象的引用更改为其他对象时。

public void DoSomething(ref A myObject)
{
   myObject = new A(); // The object in the calling function is now the new one 
}

这可能不是他们想要做的,也不需要ref

【讨论】:

    【解决方案2】:

    class A
    {
        public string Blah { get; set; }
    }
    
    void Do (ref A a)
    {
        a = new A { Blah = "Bar" };
    }
    

    然后

    A a = new A { Blah = "Foo" };
    Console.WriteLine(a.Blah); // Foo
    Do (ref a);
    Console.WriteLine(a.Blah); // Bar
    

    如果只是

    void Do (A a)
    {
        a = new A { Blah = "Bar" };
    }
    

    然后

    A a = new A { Blah = "Foo" };
    Console.WriteLine(a.Blah); // Foo
    Do (a);
    Console.WriteLine(a.Blah); // Foo
    

    【讨论】:

    • +1 是关于 Oded 所谈论内容的明确示例,即使它已经相当清楚了。
    • 非常感谢,这一切都清楚了!
    • @Luk:很高兴它有帮助! :)
    【解决方案3】:

    如果方法应该更改存储在传递给方法的变量中的引用,则ref 关键字很有用。如果不使用ref,则无法更改引用,仅更改对象本身将在方法外可见。

    this.DoSomething(myObject);
    // myObject will always point to the same instance here
    
    this.DoSomething(ref myObject);
    // myObject could potentially point to a completely new instance here
    

    【讨论】:

      【解决方案4】:

      这并没有什么特别之处。如果您想从一个方法返回多个值,或者只是不想将返回值重新分配给您作为参数传入的对象,您可以引用变量。

      像这样:

      int bar = 4;
      foo(ref bar);
      

      代替:

      int bar = 4;
      bar = foo(bar);
      

      或者如果您想检索多个值:

      int bar = 0;
      string foobar = "";
      foo(ref bar, ref foobar);
      

      【讨论】:

      • 其实OP讲的是引用类型,不是值类型,比如int
      • 所以你是说引用不与值类型一起使用?
      • afaik,没有。值类型每次都被完全复制,即按值。这就是为什么它们被称为值类型
      • 现在我明白你的意思了。我从没想过 OP 使用了一个实际的对象。一开始读它时我很累,连续 24 小时以上。
      猜你喜欢
      • 2014-11-21
      • 2011-06-16
      • 2014-11-15
      • 1970-01-01
      • 2016-06-13
      • 2020-02-27
      • 2016-02-10
      • 1970-01-01
      • 2017-02-03
      相关资源
      最近更新 更多