继承c#generic,而类类型是继承的



这样的东西在C#中可能吗?

假设我有这个:

public class T : U
{
 ...
}

我想要这个:

public class A<T> : B<U>
{
...
}

这样我就可以在我的代码中有这个:

B<U> x = new A<T>();

你不能像写的那样拥有它,但你可以这样做:

public class A<T, U> : B<U> where T : U
{
   ...
}

然后做

B<U> x = new A<T, U>();

初始代码运行良好。。。尽管由于你使用的术语可能会有一些混乱。。。

我相信你写的代码可以更清楚地重写如下:

void Main()
{
    B<Foobar> x = new A<Wibble>();
}
// Define other methods and classes here
public class Foobar
{
}
public class Wibble : Foobar
{
}
public class B<U>
{
}
public class A<T> : B<Foobar>
{
}

需要注意的关键是,有时在泛型参数的上下文中使用U,有时将其用作具体类。

上面的代码相当于(就LINQPad编译它的IL而言):

void Main()
{
    B<U> x = new A<T>();
}
// Define other methods and classes here
public class U
{
}
public class T : U
{
}
public class B<U>
{
}
public class A<T> : B<U>
{
}

只有最后两个类使用泛型参数,而最后一个类没有将U定义为泛型参数,因此它将其视为具体类。很难说这是否是你想要的,因为你没有告诉我们你想要什么,只是给我们看了一些代码。我想你可能想要@Roy Dictus回答的两个通用参数的解决方案,但你可能想要这个。很难说

我应该注意到,我把这个答案部分归功于之前被删除的一个答案。这个答案指出代码编译得很好,这激发了我测试实际代码的灵感。遗憾的是,答案被删除了,我不能相信这个人给了我灵感。

谢谢大家。Chris这解决了我的问题,前提是我能够在下面的A<T>的构造函数中调用T的构造函数:公共类A<T>:B<Foobar>{}我该怎么做jambodev 1分钟前

在这种情况下,T是一个泛型参数,所以你必须告诉编译器T肯定是可构造的。要做到这一点,您需要约束T以确保它有一个构造函数。然后,您应该能够随时创建它的新实例(例如T foo = new T();

当然,你不能像链接基类的构造函数那样调用构造函数,因为a无论如何都不是从T派生的,它只是在泛型模式中使用T类型的对象。

public class A<T> : B<Foobar> where T :new()
{
    public T MyInstance {get; set;}
    public A()
    {
        MyInstance = new T();
    }
}
void Main()
{
    B<Foobar> x = new A<Wibble>();
    Wibble y = ((A<Wibble>)x).MyInstance;
}

(这个代码取代了我第一个代码块中的等效方法)

请注意,y是在x的conscrutor中创建的Wibble类型的对象。还请注意,我需要在访问x之前强制转换x,因为B<Foobar>对泛型类型Wibble的使用一无所知。

现在还不完全清楚该怎么办(类名没有帮助,我的大脑在处理t类)。Roy Dictus的答案是你想要的吗?或者Chris的答案就是你想要的?我对这个问题的解释与前者不同,比如这个

    public class MyBaseClass  {}
    public class MyClass : MyBaseClass {}
    interface IB<out T>{}
    public class B<T> : IB<T> { }
    public class A<T> : B<T>   {}
    static void Main(string[] args)
    {
        IB<MyBaseClass> myVar = new A<MyClass>();
    }

关键是接口支持协方差,而类则不支持。

最新更新