如何从C#</t>中的Action <t>委托调用非静态方法

时间:2014-12-12 06:19:02

标签: c# generics static delegates

由于我正在为要执行的某个操作编写一个通用概念,我需要在Action委托中调用一些非静态方法。而且,我的代码中没有一个是静态的。但我仍然不能在Action定义中调用非静态方法。 这是我的代码 -

private Dictionary<string, Action<object>> m_dicUndoRedoAction = new Dictionary<string, Action<object>>();
m_dicUndoRedoAction.Add("DeleteClass", DeleteClassFromeNode );

并且这里是DeleteClass的定义

private Action<object> DeleteClassFromeNode =
  data =>
  {
    Tuple<itemType1, itemType2> items = data as Tuple<itemType1, itemType2>;
    if (items != null && items.Item2 != null)
    {
      DeleteClass(items.Item2); // This is my non static method in the same class.
    }
  };

以及我如何调用代表

private void Undo_Executed(object sender, ExecutedRoutedEventArgs e)
{
  object temp;
  if (UndoRedoAction.DoUndo(out temp))
  {
    m_dicUndoRedoAction["DeleteClass"].Invoke(temp);
  }
}

正如编译器所说

  

字段初始值设定项不能引用非静态字段,方法或   property&#39; DeleteClassFromeNode&#39;

我还查看了Action文章的MSDN参考,但MS没有提到,Action是隐式静态还是我走错路? 我也从静态方法中查看了一些非静态调用,但没有一个是令人满意的解释。 如果有人提供低水平的解释,我将不胜感激。

  

回应彼得的解释

虽然初始化程序在构造函数完成之前运行,但它并不能使它在构造函数执行之间触发委托。即使您将在ILDASM中查找其汇编代码,它也会将实际操作字段显示为非静态,但将匿名委托对象缓存为静态。为什么编译器会出现这种不同的行为?

enter image description here

1 个答案:

答案 0 :(得分:4)

正如编译器告诉您的那样,您被禁止在初始化程序中使用非静态成员。这是因为初始化程序在构造函数完成之前运行,因此使用非静态成员不一定安全。

相反,只需在构造函数中执行初始化:

public MyClass()
{
    DeleteClassFromeNode = data =>
    {
        Tuple<itemType1, itemType2> items = data as Tuple<itemType1, itemType2>;
        if (items != null && items.Item2 != null)
        {
          DeleteClass(items.Item2); // This is my non static method in the same class.
        }
    };

    // Other initialization code can go here (or before...whatever is most appropriate)
}