派生类的C#方法作为基础构造函数中的委托

NNN*_*NNN 8 c# static delegates

为什么以下C#不合法?是否存在正确的解决方法?

public class Base
{
    public Base(Func<double> func) { }
}

public class Derived : Base
{
    public Derived() : base(() => Method()) <-- compiler: Cannot access non-static method 'Method' in static context
    {
    }

    public double Method() { return 1.0; }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

它在基础构造函数的参数中有效地引用了"this",这是你不能做到的.

如果你的代表真的不需要访问this(你的样本没有),你可以让它静态.您还可以使用方法组转换使其更简单:

public class Base
{
    public Base(Func<double> func)
    {
        double result = func();
    }
}

public class Derived : Base
{
    public Derived() : base(Method)
    {
    }

    public static double Method() { return 1.0; }
}
Run Code Online (Sandbox Code Playgroud)

如果你确实需要使用"this",你可以:

  • 使其成为虚拟方法,而不是调用委托
  • 使它成为一个静态方法,它采用适当的实例,例如

    public class Base
    {
        public Base(Func<Base, double> func)
        {
            double result = func(this);
        }
    }
    
    public class Derived : Base
    {
        public Derived() : base(x => Method(x))
        {
        }
    
        private static double Method(Base b) 
        {
            // The documentation would state that the method would only be called
            // from Base using "this" as the first argument
            Derived d = (Derived) b;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)