簡體   English   中英

C#抽象泛型方法調用

[英]C# abstract generic method call

與下面的抽象類:

public abstract class A
{
    public static string MyMethod()
    {
        return "a";
    }
}

為什么我不能建立這個派生的抽象類:

public class B<T> where T : A
{
    public void AnotherMethod()
    {
        var S1 = base.MyMethod();    // not allowed
        var S2 = T.MyMethod();       // not allowed
    }
}

我不明白為什么,因為MyMethod將在T類型中可用。

您的問題中存在兩個誤解,共同阻止了您的嘗試都奏效。

首先,您的B類絕不是從A類派生的,您只說過它采用了必須從A繼承的通用參數。

其次,正如用戶@recursive指出的那樣,靜態方法不參與繼承,因此MyMethod僅可用作A.MyMethod()

如果刪除static修飾符並使B從A繼承而不是使用泛型,則至少可以使第一次嘗試起作用。

// Removed the static modifier
public abstract class A
{
    public string MyMethod()
    {
        return "a";
    }
}

// Made B inherit directly from A
public class B : A
{
    public void AnotherMethod()
    {
        var S1 = base.MyMethod(); //base technically isn't required
    }
}

除了A.MyMethod是靜態的這一事實之外,它顯然將不起作用,因為任何靜態都不參與繼承,即使您將其設置為非靜態,它也仍然無法工作。 例如,這將不起作用:

public abstract class A {
   public string MyMethod() {
      return "a";
   }
}

public class B<T> where T : A {
   public void AnotherMethod() {
      var S1 = base.MyMethod();    // Line 1
      var S2 = T.MyMethod();       // Line 2
   }
}

為什么?

您說的where T : A ,這意味着T必須是從A派生的類型。 您的類B<T不是A的派生類型,因此第1行將不起作用。

但是為什么2號線不起作用?

T是一種類型,如果T繼承了A ,則類型T對象將能夠做到這一點。 如果您這樣更改它,它將起作用:

public abstract class A {
   public string MyMethod() {
      return "a";
   }
}

public class B<T> where T : A {
   public void AnotherMethod(T t) {
         t.MyMethod();
   }
}

public class C : A {

}

public class BClosed : B<C> {
   public void Foo(C c) {
      c.MyMethod();
      this.AnotherMethod(c);
   }
}

在上面的代碼中, C派生了A ,這是您的限制。 然后BClosed關閉說TC的泛型類型,因此現在您可以調用A MyMethod和泛型的AnotherMethod

另外,當您有通用類時,應使用通用類型,否則我看不到用法。 因此,這是沒有用的,因為它沒有通用代碼:

public class B<T> where T : A {
   public void AnotherMethod() {

   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM