存储非静态方法的参考

Jon*_*ood 3 .net c# delegates

我正在尝试创建一个值集合,每个值对应一个动作.这样,我将能够在集合中搜索特定值,然后以通用方式调用关联的操作.

所以,这是我第一次尝试:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,新的声明CommandInfo里面Commands收集给我的错误:

字段初始值设定项不能引用非静态字段,方法或属性'MyNameSpace.MyClass.AbcAction(MyNameSpace.RunArgument)'

当然必须有一种方法来存储对像这样的非静态方法的引用.有人可以帮我吗?

Jon*_*eet 6

当然必须有一种方法来存储对像这样的非静态方法的引用.有人可以帮我吗?

有,不在字段初始化程序中.所以这很好用:

public List<CommandInfo> Commands = new List<CommandInfo>();

public MyClass()
{
    Commands.Add(new CommandInfo { Name = "abc",
                                   Action = AbcAction });
}
Run Code Online (Sandbox Code Playgroud)

...或在构造函数中执行整个赋值.请注意,这与代表没有任何关系 - 这是偶然的,因为你有效地指的是this.AbcAction.在其他方面,它等同于这个问题:

public class Foo
{
    int x = 10;
    int y = this.x; // This has the same problem...
}
Run Code Online (Sandbox Code Playgroud)

(我希望你真的没有公共领域,当然......)


shf*_*301 5

问题不在于您不能存储对非静态成员的引用,而是不能在字段初始化器中引用非静态成员。字段初始化程序只能引用静态或常量值。将的初始化Commands移到构造函数中,它将起作用。

public class CommandInfo
{
    public string Name { get; set; }
    public Action<RunArgument> Action { get; set; }
}

public class MyClass
{
    public List<CommandInfo> Commands;

    public MyClass 
    {
        Commands = new List<CommandInfo>
        {
            new CommandInfo { Name = "abc", Action = AbcAction }
        };
    }

    public void AbcAction(RunArgument arg)
    {
        ; // Do something useful here
    }
}
Run Code Online (Sandbox Code Playgroud)