除了一个事实,即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
所以现在你可以拨打电话MyMethod
A
和AnotherMethod
你的通用。
此外,当你有一个泛型类,你应该使用泛型类型,否则我没有看到使用。所以这是没用的,因为它没有通用的代码:
public class B<T> where T : A {
public void AnotherMethod() {
}
}
在C#中,静态方法调用总是在编译时静态解析。静态方法不参与继承。 – recursive
为什么'var S2 = A.MyMethod();',因为你知道上面的'A'? –
'基地。MyMethod()'不会工作,因为B不会继承A,它的类型参数仅限于A的实现,这是递归注释的来源。 – Phaeze