【发布时间】:2015-09-28 12:51:56
【问题描述】:
假设我有一组类/接口:
class ObjectData { }
class UnitData : ObjectData { }
class Component1Data : UnitData { }
class Component2Data : UnitData { }
interface IObject { }
interface IUnit : IObject { }
interface IComponent1 : IUnit { }
interface IComponent2 : IUnit { }
abstract class Object<D, O, I>
where D : ObjectData
where O : Object<D, O, I>, I, new()
where I : IObject
{ }
这里的主要兴趣点是Object 类,它是某些层次结构中的基本泛型类。类型参数“O”是一种指定从Object 派生的实际类的类型的方法。因此,可以在没有问题的情况下声明和编译这样的内容:
class Unit : Object<UnitData, Unit, IUnit>, IUnit { }
但我想做的是定义另一个从 Object 派生的通用“第二级”类,它也应该作为几个类似“第三级”实体的基类。它必须是非抽象的,因为它也是某种实体。所以我需要定义这样的东西:
class Unit<D, I> : Object<D, Unit<D, I>, I>, IUnit
where D : UnitData
where I : IUnit
{ }
class Component1 : Unit<Component1Data, IComponent1>, IComponent1 { }
class Component2 : Unit<Component2Data, IComponent2>, IComponent2 { }
它会产生以下编译错误:
error CS0311: The type 'Unit<D, I>' cannot be used as type parameter 'O' in the generic type or method 'Object<D, O, I>'. There is no implicit reference conversion from 'Unit<D, I>' to 'I'.
问题是为什么?在我看来,如果Unit<D, I> 正在实现IUnit,并且参数“I”被指定为where I : IUnit,那么一切都应该没问题。我就是这么看的。我没看到什么?
【问题讨论】:
-
这一定是我见过的最复杂的泛型使用...
-
O将如何在Object<D, O, I>内部使用?请发布示例代码。 -
例如这样: public static O Create(D data) { return data != null ?新 O { 数据 = 数据 } : null; } 公共 D 数据 { 获取;私人套装; }
-
我想引用 Eric Lippert(C# 的权威,因为我不是我自己):“更具体地说,我会说你在滥用泛型。事实上,你已经类型关系太复杂以至于你无法分析自己,这表明你应该简化整个事情;如果你没有保持所有类型关系直截了当并且你写了东西,那么你的用户肯定无法保持直截了当任何一个。” stackoverflow.com/questions/17434851/…
-
也许埃里克是对的,但这能回答我的问题吗?
标签: c# generics inheritance