在 .NET 中实现泛型的方式要求Foo<T>无论T. 除其他外,所有成员都Foo<T>必须具有相同的成员,只是成员可以包含T在其定义中。如果Foo<T>可以继承自T,那么知道暴露了哪些成员Foo<T>就需要知道暴露了哪些成员,这对于 a和 aT当然可能完全不同。如果知道这将仅用于派生自 eg 的类型,则可以定义 a ,但这仅允许将 a用作 -- 而不是用作 a 。Foo<Automobile>Foo<Cat>Foo<T>Animalclass Foo<T> : Animal where T:AnimalFoo<Cat>AnimalCat
然而,在许多情况下,真正需要的不是Foo<T>实际继承的类型T,而是能够创建一个行为大多类似于T,但有一些差异的对象。.NET Framework 也不允许直接执行此操作,但有一些库可以为此目的自动生成代理对象。给定一个接口和一个或多个对象,每个对象都实现一些接口成员,并且共同实现所有这些成员,代理生成器将创建(在运行时!)一个新类,该类包含对提供的对象的引用并实现该接口通过为每个接口方法创建一个类方法,该类方法链接到传入对象之一上的相应方法。
Note that although the method which creates these new classes will be generic, the classes themselves will not be. It may be that myProxyMaker.Create<IFoo>(IFlyingMammal) returns a proxy8675309 and a myProxyMaker.Create<ISwimmingMammal> returns a proxy24601. Because they are completely different classes, the fact that IFlyingMammal has different members from ISwimmingMammal would pose no problem. The fact that the classes might have ugly machine-generated names wouldn't really matter because one wouldn't be declaring variables of type proxy8675309 or proxy24601, but instead types IFlyingMammal and ISwimmingMammal.