繁体   English   中英

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

[英]C# method from derived class as delegate in base constructor

为什么以下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; }
}

它在基础构造函数的参数中有效地引用了“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; }
}

如果你确实需要使用“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; } } 

另一个解决方案是将委托的初始化推迟到派生类:

public class Base {
   protected Func<double> DoubleFunc { get; set; }

   protected Base() {
      // defer initialization by not setting DoubleFunc
      // or another possibility is to set it to a dummy function:
      DoubleFunc = () => 0;
   }

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

public class Derived : Base {
   public Derived() {
      DoubleFunc = Method;
   }

   public double Method() { return 1.0; }
}

基本上,您会收到编译器错误,因为您在没有类Derived实例的情况下引用了instance-method Method 调用base ,构造函数尚未完成,您还没有类的实例。 如果你做Method static它会工作得很好。

您是否尝试过编译器指示的Method()静态? 问题是Derived的实例在构造函数返回之后才可用,因此您无法在其上调用实例方法。

“解决方法”是使Method()成为静态方法。

我无法解释为什么这不起作用的技术原因,但实际上你试图在一个尚不存在的实例上调用一个方法。 怎么可能有用呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM