AST*_*eam 0 c# reference instance
我有一个类Node如下:
public class Node
{
public Dictionary<string, string> dictionary;
public Node(Dictionary<string, string> dictionary)
{
this.dictionary = dictionary;
}
public void CreateNode()
{
this.dictionary.Add("1", "String1");
Dictionary<string, string> dictionary1 = new Dictionary<string, string>();
Console.WriteLine(this.dictionary["1"]);
Node tmp = new Node(dictionary1);
tmp.dictionary = this.dictionary;
Console.WriteLine(tmp.dictionary["1"]);
tmp.AddE(tmp, "String2","2");
Console.WriteLine(this.dictionary["2"]);
}
public void AddE(Node tmp,String text,string c)
{
tmp.dictionary.Add(c,text);
}
}
Run Code Online (Sandbox Code Playgroud)
Node有一个包含字符串键和值的字典,一个带参数的构造函数,一个CreateNode()方法,它将一个项添加到字典中并创建另一个Node.现在,在tmp.dictionary = this.dictionary之后; 在tmp.dictionary上添加了另一个项目,但是它也添加在this.dictionary中(我不希望发生这种情况,我很想丢失).
主要方法:
static void Main(string[] args)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Node n = new Node(dictionary);
n.CreateNode();
}
Run Code Online (Sandbox Code Playgroud)
输出是:
String1
String1
String2
Run Code Online (Sandbox Code Playgroud)
对于这行代码Console.WriteLine(this.dictionary ["2"]); 它应该显示此错误KeyNotFoundException:给定的键不存在于字典中.因为我没有在this.dictionary上添加一个带有键"2"的项目.希望我清楚自己.
因为我没有在this.dictionary上添加一个带有键"2"的项目.
是的,你做到了.你通过这个电话做到了:
tmp.AddE(tmp, "String2","2");
Run Code Online (Sandbox Code Playgroud)
这会将一个带有键"2"和值"String2"的条目添加到由tmp... this引用的字典中,这是由于此行引用的相同字典:
tmp.dictionary = this.dictionary;
Run Code Online (Sandbox Code Playgroud)
您使用该行创建的第二个字典:
Dictionary<string, string> dictionary1 = new Dictionary<string, string>();
Run Code Online (Sandbox Code Playgroud)
...有资格进行垃圾收集,因为事后没有任何内容.它最初是新tmp节点中的字典,但是您可以将其替换为"this"中对同一字典的引用,如上所示.
附注:尽量避免构造这样令人困惑的代码.像这样的方法是一个问题的方法:
public void AddE(Node tmp,String text,string c)
{
tmp.dictionary.Add(c,text);
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例方法,但它不使用"当前"实例的任何状态(this指的是) - 相反,它会修改传入的节点的状态.最好写成:
public void AddE(String text, string c)
{
this.dictionary.Add(c,text);
}
Run Code Online (Sandbox Code Playgroud)
......换句话说,修改状态this.(在值之后传递密钥仍然很奇怪,并且一个被调用的参数c没有提供关于它的用途的提示,但这是另一回事.)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |