0

这是对我之前的问题的扩展: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. 正如我在开头所描述的,我希望GetSimpleClone()in 的方法IAddress返回一个 type 的对象,IAddress而 in 的同一个方法IVenue应该返回一个 type 的对象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; }
}

我真的看不到这个问题的解决方案,并希望您能提供任何帮助,即使只是说根本没有解决方案。:)

提前致谢...

4

1 回答 1

1

为此,您需要引入另一个泛型:

public interface IPerson<T> : IEntity<IPerson<T>>
    where T : IAddress<T>
{
   IAddress<T> Address { get; set; }
}

我能想到的更好的解决方案是将安全问题放在一边,并使用IAddress通用方法创建一个良好的基本接口,例如getAddressString,并将其用于您可能想要的所有类型的地址。

于 2013-03-03T16:26:38.323 回答