繁体   English   中英

使用out引用将委托添加到动作字典时出错

[英]Error while adding delegate to Action Dictionary using an out reference

似乎当我尝试通过使用TryToGetValue方法获得的引用添加委托时,将委托添加到存储在DictionaryAction失败。

这是重现该错误的示例:

void Foo()
{
  Console.WriteLine("Foo");
}
void Bar()
{   
  Console.WriteLine("Bar");
}

Dictionary<int, Action> dic = new Dictionary<int, Action>();    

dic[3] = delegate{};
dic[3] += Foo;

Action ac;
if (dic.TryGetValue(3,out ac))
{
  Console.WriteLine("Found");
  ac += Bar;
}
dic[3]();

输出:

Found
Foo

找到了该值,但似乎acdic[3]是对不同对象的引用(不打印Bar )。

谁能解释我发生了什么事? 用什么确切填充out parameter 由于Action是类,不应该ac基准点存储到同一个对象Dictionary

您的示例可以简化(不包括字典):

  void Foo() {
    Console.WriteLine("Foo");
  }

  void Bar() {
    Console.WriteLine("Bar");
  }

  ...
  Action x = Foo;
  Action y = x;

  if (Object.ReferenceEquals(x, y))
    Console.WriteLine("x was equal to y"); 

  // creates new delegate instance: 
  // x = x + Bar; 
  //   that is equal to 
  // x = Action.Combine(x, Bar);
  //   so x is not equal to y any longer:
  // x is a combined delegate (Foo + Bar)
  // y is a delegate to Foo (an old version of x)
  //   such a behavior is typical for operators (+, +=, etc.): 
  //   when we declare "public static MyType operator + (MyType a, MyType b)"
  //   it means that a new object "c" will be created that'll equal to sum of a and b 
  x += Bar; 

  if (Object.ReferenceEquals(x, y))
    Console.WriteLine("x is still equal to y");

  y();

输出为:

x等于y

这种行为的原因在于+ =操作算法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM