是这样的可能在C#中?继承与C#泛型,而类继承类型
假设我有这样的:
public class T : U
{
...
}
,我想这一点:
public class A<T> : B<U>
{
...
}
,这样我可以在我的代码有这样的:
B<U> x = new A<T>();
是这样的可能在C#中?继承与C#泛型,而类继承类型
假设我有这样的:
public class T : U
{
...
}
,我想这一点:
public class A<T> : B<U>
{
...
}
,这样我可以在我的代码有这样的:
B<U> x = new A<T>();
这是不完全清楚你要做什么(班级名称没有帮助,我的大脑正在与T级奋斗)。是罗伊Dictus的回答你想要的,或者也许克里斯的答案是你在找什么?我解释这个问题以不同的方式从任前的,像这样的
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>();
}
你不能把它完全像你写的,但你可以这样做:
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,有时您将它用作具体类。
上面的代码是等效(在IL的字词LINQPad它编译到)到:
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
:public class 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的conscructor中。还请注意,在访问它之前我需要投射x,因为B<Foobar>
对使用通用类型Wibble
一无所知。
他可以完全按照他所写的来写,它可能并不意味着他想要的。但是,如果他愿意,他可以准确地输入他认为有效的C#的内容。 :) – Chris 2012-02-21 16:22:15
好的,我写的并不完全是我的意思:) – jambodev 2012-02-22 08:17:07