簡體   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