代码之家  ›  专栏  ›  技术社区  ›  Greg

c#-我是否应该使用“ref”通过引用方法来传递集合(例如List)?

  •  35
  • Greg  · 技术社区  · 14 年前

    我应该使用“ref”通过引用方法来传递列表变量吗?

    答案是“ref”是不需要的(因为列表将是一个参考变量),但是为了便于阅读,把“ref”放进去?

    3 回复  |  直到 14 年前
        1
  •  32
  •   Lou Franco    14 年前

    不,除非要更改变量引用的列表,否则不要使用ref。如果您只想访问列表,请不要使用ref。

    如果你做了一个参数ref,你的意思是调用者应该期望他们传入的参数可以被分配给另一个对象。如果你不这样做,那么它就不能传达正确的信息。您应该假设所有的C#开发人员都知道一个对象引用正在传入。

        2
  •  68
  •   recursive    14 年前

    void Method1(Dictionary<string, string> dict) {
        dict["a"] = "b";
        dict = new Dictionary<string, string>();
    }
    
    void Method2(ref Dictionary<string, string> dict) {
        dict["e"] = "f";
        dict = new Dictionary<string, string>();
    }
    
    public void Main() {
        var myDict = new Dictionary<string, string>();
        myDict["c"] = "d";
    
        Method1(myDict);
        Console.Write(myDict["a"]); // b
        Console.Write(myDict["c"]); // d
    
        Method2(ref myDict); // replaced with new blank dictionary
        Console.Write(myDict["a"]); // key runtime error
        Console.Write(myDict["e"]); // key runtime error
    }
    
        3
  •  13
  •   Esteban Araya    14 年前

    ref 在您的场景中,它也不会有助于可读性。