存储非静态方法的参考

时间:2012-10-09 21:06:56

标签: c# .net 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
    }
}

在这种情况下,CommandInfo集合中新Commands的声明会给我一个错误:

  

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

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

2 个答案:

答案 0 :(得分:6)

  

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

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

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

public MyClass()
{
    Commands.Add(new CommandInfo { Name = "abc",
                                   Action = AbcAction });
}

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

public class Foo
{
    int x = 10;
    int y = this.x; // This has the same problem...
}

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

答案 1 :(得分:4)

问题不在于您无法存储对非静态成员的引用,而是您无法在字段初始值设定项中引用非静态成员。字段初始值设定项只能引用静态值或常量值。将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
    }
}
相关问题