继承c#泛型,而类类型是继承的
在C#中可能出现类似的情况吗 假设我有:继承c#泛型,而类类型是继承的,c#,generics,inheritance,C#,Generics,Inheritance,在C#中可能出现类似的情况吗 假设我有: public class T : U { ... } 我想要这个: public class A<T> : B<U> { ... } 公共A类:B类 { ... } 因此,我可以在代码中包含以下内容: B<U> x = new A<T>(); bx=新的A(); 现在还不完全清楚您要做什么(类名没有帮助,我的大脑正在与t类斗争)。罗伊·迪克图斯的答案是你想要的,或者克里斯的答案是你想要的?我用不同
public class T : U
{
...
}
我想要这个:
public class A<T> : B<U>
{
...
}
公共A类:B类
{
...
}
因此,我可以在代码中包含以下内容:
B<U> x = new A<T>();
bx=新的A();
现在还不完全清楚您要做什么(类名没有帮助,我的大脑正在与t类斗争)。罗伊·迪克图斯的答案是你想要的,或者克里斯的答案是你想要的?我用不同于前者的方式解释了这个问题,就像这样
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>();
}
公共类MyBaseClass{}
公共类MyClass:MyBaseClass{}
接口IB{}
公共类B:IB{}
公共类A:B{}
静态void Main(字符串[]参数)
{
IB myVar=新的A();
}
关键是。你不能像你写的那样拥有它,但你可以这样做:
public class A<T, U> : B<U> where T : U
{
...
}
公共类A:B,其中T:U
{
...
}
然后呢
B<U> x = new A<T, U>();
bx=新的A();
最初的代码工作正常。。。虽然由于您使用的术语可能会有一些混淆
我相信您编写的代码可以更清楚地重写如下:
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>
{
}
(此代码替换我的第一个代码块中的等效方法)
请注意,y是在x的conscructor中创建的Wibble类型的对象。还请注意,我需要在访问它之前强制转换x,因为
B
对泛型类型的使用一无所知Wibble
他可以完全按照自己编写的那样使用它,这可能并不意味着他想要它。但如果他愿意的话,他可以把他输入的内容准确地作为有效的C好吧,我写的并不完全是我的意思:)谢谢大家。Chris这解决了我的问题,前提是我能够在下面的:公共类A:B{}的构造函数中调用T的构造函数。我怎么做?
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>
{
}
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;
}