C#抽象泛型方法调用

C# abstract generic method call

摘要如下class:

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

为什么我不能构建这个派生摘要class:

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 class 不是从 A class 以任何方式派生的,你只是说它需要一个必须继承自的通用参数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 的派生类型。您的 class 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 所以现在你可以调用 AMyMethod 和泛型的 AnotherMethod

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

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

   }
}