这是我上一个问题的扩展:Type safety through inheritance
我创建了一个新问题,而不是更新我的旧问题,因为这个问题深入这个主题。
我最初的目的是声明一个返回实现类类型的对象的方法。一种这样的方法可能看起来像下面的GetSimpleClone():
我有一个基接口IEntity,它声明了方法GetSimpleClone(),并由其他几个接口实现,例如IPerson。
public interface IEntity<T> : where T : IEntity<T>
{
T GetSimpleClone();
}
public interface IPerson : IEntity<IPerson>
{
}接口IAddress也实现了IEntity。但是,IVenue从IAddress继承了另一个接口。正如我在开头所描述的,我希望IAddress中的GetSimpleClone()方法返回IAddress类型的对象,而IVenue中的同一方法应该返回IVenue类型的对象。因此,IAddress的声明不同于IPerson,因为它必须声明自己的泛型类型:
public interface IAddress<T> : IEntity<T> where T : IAddress<T>
{
}
public interface IVenue : IAddress<IVenue>
{
} 现在的问题是,IPerson引用了IAddress,可以理解,编译器迫使我定义IAddress的泛型类型。
public interface IPerson : IEntity<IPerson>
{
IAddress<"Compiler: Define Type!!"> Address { get; set; }
}我真的看不到这个问题的解决方案,并感谢您的任何帮助,即使只是说根本没有解决方案。:)
先谢谢你...
发布于 2013-03-04 00:26:38
要实现这一点,您需要引入另一个泛型:
public interface IPerson<T> : IEntity<IPerson<T>>
where T : IAddress<T>
{
IAddress<T> Address { get; set; }
}我能想到的更好的解决方案是把安全问题放在一边,用getAddressString这样的通用方法创建一个良好的基本IAddress接口,并将其用于您可能想要的所有类型的地址。
https://stackoverflow.com/questions/15187654
复制相似问题