【问题标题】:Storing Reference to Non-Static Method存储对非静态方法的引用
【发布时间】:2012-10-10 05:13:43
【问题描述】:

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

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

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
    }
}

在这种情况下,Commands 集合内的新 CommandInfo 声明给了我错误:

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

肯定有一种方法可以像这样存储对非静态方法的引用。有人可以帮帮我吗?

【问题讨论】:

    标签: c# .net delegates


    【解决方案1】:

    肯定有一种方法可以像这样存储对非静态方法的引用。有人可以帮帮我吗?

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

    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...
    }
    

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

    【讨论】:

    • 谢谢,但我不太明白为什么我的语法不被接受,而你的却被接受。这是有原因的吗?
    • @JonathanWood:是的 - 你正试图在字段初始化器中构造它,你不能在字段初始化器中引用this。看看我的编辑是否有帮助。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 2018-11-25
      • 1970-01-01
      相关资源
      最近更新 更多