How to call non-static methods from an Action <T> delegate in C #

Since I am writing a generalized concept to perform an action, I need to call some non-stationary method in the Action deletion. Also, none of them are static in my code. But still, I cannot call a non-static method inside the Action definition. Here is my code -

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

and here is the definition of 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.
    }
  };

and here, as I call the delegate

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

as the compiler says

A field initializer cannot reference non-static fields, a method, or the 'DeleteClassFromeNode' property

MSDN , MS , , ? , . , - .

, . ILDASM, , . ?

enter image description here

+4
1

, . , , .

:

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)
}
+4

All Articles