I’m trying to create a collection of values that each correspond to an action. This way, I’ll be able to search the collection for a particular value and then call the associated action in a generic way.
So, here was my first stab at it:
public class CommandInfo
{
public string Name { get; set; }
public Action<RunArgument> Action { get; set; }
}
public class MyClass
{
public List<CommandInfo> Commands = new List<CommandInfo>
{
new CommandInfo { Name = "abc", Action = AbcAction } // <== ERROR HERE
};
public void AbcAction(RunArgument arg)
{
; // Do something useful here
}
}
In this case, the declaration of the new CommandInfo inside the Commands collection gives me the error:
A field initializer cannot reference the non-static field, method, or property ‘MyNameSpace.MyClass.AbcAction(MyNameSpace.RunArgument)’
Surely there must be a way to store a reference to a non-static method like this. Can someone help me out?
There is, just not within a field initializer. So this works fine:
… or perform the whole assignment within the constructor. Note that this doesn’t really have anything to do with delegates – it’s incidental, on the basis that you’re effectively referring to
this.AbcAction. In every other way, it’s equivalent to this problem:(I hope you don’t really have a public field, of course…)