C#抽象泛型方法调用



具有以下抽象类:

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()使用

如果删除静态修饰符并使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,所以现在可以调用泛型的AMyMethodAnotherMethod

此外,当你有一个泛型类时,你应该使用泛型类型,否则我看不到它的用途。所以这是无用的,因为它没有通用代码:

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

最新更新