Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - should I use "ref" to pass a collection (e.g. List) by reference to a method?

Should I use "ref" to pass a list variable by reference to a method?

Is the answer that "ref" is not needed (as the list would be a reference variable), however for ease in readability put the "ref" in?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A dictionary is a reference type, so it is not possible to pass by value, although references to a dictionary are values. Let me try to clear this up:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...