与泛型参数和抽象类泛型 [英] Generics with Generic Parameters and Abstract class
问题描述
我有两个通用基础类。第二泛型类有一流的它的参数的约束。
I've got two generic base classes. The second generic class has a constraint on its parameter of the first class.
abstract class FirstClass<T> {...}
abstract class SecondClass<U> where U : FirstClass {...}
这是不行的,因为没有定义的Firstclass。所以,我需要做到这一点。
This does not work, because FirstClass is not defined. So I need to do this.
abstract class FirstClass<T> {...}
abstract class SecondClass<U, T> where U : FirstClass<T> {...}
其中一期工程。然而,这使得实施这些抽象类难看。
Which works. However, this makes implementing these abstract classes ugly.
class SomeClass {...}
class MyFirstClass : FirstClass<SomeClass> {...}
class MySecondClass : SecondClass<MyFirstClass, SomeClass> {...}
由于我指定SomeClass的两倍这似乎是多余的给我。有声明它以这样一种方式,Ť从的Firstclass自动是在U为二等的方法。我真的很喜欢这个样子的。
This seems redundant to me because I'm specifying SomeClass twice. Is there a way to declare it in such a way that T from FirstClass is automatically the U for SecondClass. What I would really like this to look like is.
class SomeClass {...}
class MyFirstClass : FirstClass<SomeClass> {...}
class MySecondClass : SecondClass<MyFirstClass> {...}
虽然我怀疑这个确切的情况是可能的,是有一个更清洁做什么,我试图做?
While I doubt this exact scenario is possible, is there a cleaner what to do what I am trying to do?
修改
有几个人建议作出IFirstClass接口。但我的定义更接近这一点。
Several people have suggested making an IFirstClass interface. But my definitions are closer to this.
class FirstClass<T>
{
public T MyObj { get; set; }
}
class SecondClass<U, T> where U : FirstClass<T>
{
U MyFirstClass { get; set; }
}
通过一个界面我无法从二等访问MyFirstClass.MyObj。虽然我可以创建一个对象牛逼MyObj中获得{;组; }
上IFirstClass,然后用新
来隐藏它,Silverlight的罚全中绑定一个合适的,如果我这样做。
With an interface I cannot access MyFirstClass.MyObj from SecondClass. While I could create a object T MyObj { get; set; }
on IFirstClass, then use new
to hide it, silverlight throws a fit in the binding if I do this.
推荐答案
如果您在实际使用泛型类型参数的Firstclass
(如,从您的编辑,这听起来像你这样),那么没有,你要找什么不幸的是不可能的。编译器不被相关类型参数和那些不区分。
If you are actually using the generic type arguments to FirstClass
(as, from your edit, it sounds like you are), then no, what you're looking for is unfortunately not possible. The compiler does not differentiate between type arguments that are related and those that are not.
这篇关于与泛型参数和抽象类泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!