c# - 我应该使用"ref"通过引用方法传递集合(例如List)吗?

Gre*_*reg 37 c# methods pass-by-reference

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

答案是不需要"ref"(因为列表将是一个参考变量),但为了便于阅读,将"ref"放入?

rec*_*ive 59

字典是引用类型,因此虽然对字典的引用是值,但是不能通过值传递.让我试着澄清一下:

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
}
Run Code Online (Sandbox Code Playgroud)


Lou*_*nco 28

不,除非您想要更改变量引用的列表,否则不要使用ref.如果您只想访问列表,请在没有参考的情况下进行.

如果您创建参数ref,则表示调用者应该期望他们传入的参数可以分配给另一个对象.如果你不这样做,那么它没有传达正确的信息.您应该假设所有C#开发人员都了解正在传入对象引用.


Est*_*aya 10

ref在您的场景中您不需要,也不会有助于提高可读性.

ref仅在您打算更改变量引用的内容时使用,而不是它引用的对象的内容.那有意义吗?