具有通用参数和抽象类的泛型 [英] Generics with Generic Parameters and Abstract class

查看:16
本文介绍了具有通用参数和抽象类的泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通用基类.第二个泛型类对其第一个类的参数有约束.

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 中的 T 自动成为 SecondClass 的 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; }
}

使用接口我无法从 SecondClass 访问 MyFirstClass.MyObj.虽然我可以创建一个 对象 T MyObj { get;放;} 在 IFirstClass 上,然后使用 new 隐藏它,如果我这样做,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆