c# - 存储对非静态方法的引用

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

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

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?

有,只是不在字段初始值设定项中。所以这很好用:

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

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

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

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

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

关于c# - 存储对非静态方法的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12808446/

相关文章:

c# - 转换 Action <委托(delegate)>

c# - 调试 C# - 堆栈溢出异常?

c# - 无法启动 ASP.NET Web 服务器和无法切换 Mono 环境

.net - SandCaSTLe 帮助文件生成器 : Search not working

.net - 有人知道用于对SaaS用户进行计费和身份验证的服务吗?

c# - 为什么 c# 不保留匿名委托(delegate)调用的上下文?

c# - 我可以使用 REST API 检测 Smartsheet 中的单元格属性(例如颜色)吗

c# - EF Core 属性值转换在派生实体配置中不起作用

c# - 更有效地监视 Active Directory 中的组成员身份 (C# .NET)

c# - 将事件从 asp.net 用户控件公开到容器 Web 表单页面