C#学习 - 函数参数什么时候需要用ref关键字

提一个问题,函数中有一个Dictionary<string, string>类型的参数,函数中会增加或修改Dictionary中的内容,那么参数中要使用ref关键字么?

答案是:不需要!除非你要改变该参数所引用的Dictionary!

看一个例子就明白了:

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
}

猜你喜欢

转载自blog.csdn.net/jianhui_wang/article/details/79663868