[英]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
關閉說T
為C
的泛型類型,因此現在您可以調用A
MyMethod
和泛型的AnotherMethod
。
另外,當您有通用類時,應使用通用類型,否則我看不到用法。 因此,這是沒有用的,因為它沒有通用代碼:
public class B<T> where T : A {
public void AnotherMethod() {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.