C#抽象泛型方法调用

时间:2017-01-05 00:14:17

标签: c# generics abstract

使用以下类的摘要:

print('iter')

为什么我不能构建这个派生的抽象类:

__getitem__

我不明白为什么 MyMethod 将在 T 类型中提供。

2 个答案:

答案 0 :(得分:3)

您的问题中存在两种误解,即共同阻止您的尝试工作。

首先,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
    }
}

答案 1 :(得分:3)

除了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,现在您可以调用MyMethod AAnotherMethod通用。{/ p>

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

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

   }
}