c# - 您可以在静态上下文中引用非静态方法吗?

标签 c# .net

委托(delegate)的使用遵循与调用方法相同的规则 - 如果您被允许显式调用该方法,则只能通过委托(delegate)引用该方法,这意味着您不能从静态方法引用非静态方法,即使如果您实际上不调用它。有解决办法吗?

这是执行保龄球套路时使用的一些代码,注释中显示了我理想的代码行。我被迫通过静态调用(和匿名静态方法声明)来使 Frame 类代码符合我的喜好:

    public int FrameScore()
    {
        return scorer[FrameType()](this);
        // I would like it to be
        // return this.scorer[FrameType()]();
    }

    static Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>> scorer =
        new Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>>()
        {
            {LinkedFrame.FrameTypeEnum.Strike, frame => frame.StrikeScore()},
            {LinkedFrame.FrameTypeEnum.Spare, frame => frame.SpareScore()},
            {LinkedFrame.FrameTypeEnum.Regular, frame => frame.RegularScore()}
            // I would like an element to be
            // {LinkedFrame.FrameTypeEnum.Strike, StrikeScore}
        };

    private int RegularScore()
    {
        return this.Sum;
    }

    private int SpareScore()
    {
        ...
    }

    private int StrikeScore()
    {
        ...
    }

因此在某些情况下,在静态上下文中推理非静态方法是有意义的。有办法做到这一点吗?

最佳答案

也许开放实例委托(delegate)会有所帮助?

根据 MSDN: Delegate Class :

When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method. When a delegate represents an open instance method, it stores a reference to the method's entry point. The delegate signature must include the hidden this parameter in its formal parameter list; in this case, the delegate does not have a reference to a target object, and a target object must be supplied when the delegate is invoked.

归根结底,您可以使用显式 this 参数偷偷地将实例方法转换为静态方法。你可以在这里看到它是如何完成的:Simon Cooper: Introduction to open instance delegates

关于c# - 您可以在静态上下文中引用非静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7625474/

相关文章:

c# - 滚动到 UWP 的 ListView 中的新项目

c# - Winforms WPF Interop - Wpf 控件呈现为非事件状态

.net - 如何在 XP 上的 .Net 应用程序中调试 AccessViolationException

c# - 存储数字的最大数据类型

c# - 是否需要保护对 .net 集合的只读并发访问?

c# - 大型列表中的 Linq

c# - 将大文件读入字典

.net - TFS 静默修复 .sln 文件 - 有办法阻止它吗?

C# 抽象类,使用匿名而不是声明具体类?

c# - 其他环境下的类库中未加载语言资源文件