0

假设我有一个句柄类,如:

interface IHasHandle<TObject> {
     IHandle<TObject> Handle { get; }
}

interface IHandle<out TObject> {
     TObject Value { get; }
}

我想使用这个类来给我一个层次结构中派生的输出类型。我现在的样子:

interface IAnimal : IHasHandle<IAnimal> { ... }

interface IMammal : IAnimal, IHasHandle<IMammal> { ... }

interface IFeline : IMammal, IHasHandle<IFeline> { ... }

class Tiger : IFeline {
     IHandle<IAnimal> IHasHandle<IAnimal>.Handle { get { ... } }
     IHandle<IMammal> IHasHandle<IMammal>.Handle { get { ... } }
     IHandle<IFeline> IHasHandle<IFeline>.Handle { get { ... } }
     public IHandle<Tiger>   Handle { get { ... } }
}

这意味着当我有 IAnimal 时,我总是可以得到 IHandle,当我有 IMammal 时,我可以得到 IHandle,等等。

有没有人对此结构有任何一般性评论或关于如何避免所有可能的实现的想法?

4

1 回答 1

0

Even before .NET 4.0 it was possible to do things like:

interface IAnimal<TSpecies> : IHasHandle<TSpecies> where TSpecies : IAnimal<TSpecies> { ... }

interface IMammal<TSpecies> : IAnimal<TSpecies> where TSpecies : IMammal<TSpecies> { ... }

interface IFeline<TSpecies> : IMammal<TSpecies> where TSpecies : IFeline<TSpecies> { ... }

class Tiger : IFeline<Tiger> {
    IHandle<Tiger> IHasHandle<Tiger>.Handle { get { ... } }
}

Of course, this won't prevent you from making some class EvilCat : IFeline<Tiger>, but it provides quite a good way for getting rid of an extra unneeded Handle implementations in Tiger. And if you'll declare IHasHandle generic parameter as out one in this sample of code, you'll be able to cast Tiger (which implements IHasHandle<Tiger>) to IHasHandle<IMammal> for example.

于 2012-02-14T11:56:43.570 回答