部分应用泛型用于类型约束

时间:2013-09-14 12:14:14

标签: c# generics contravariance type-constraints

我目前尝试构建一个通用接口,每个(通用)类派生它都会有一个方法接受一个接受type参数的委托,并返回另一个同类型的类,只有另一个类型参数。

我尝试了以下内容:

public interface GenericInterface<out T, out SomeDerived>
    where SomeDerived<T> : GenericInterface<T, SomeDerived>
{
    SomeDerived<NT> bind<NT>(bindee<T, NT, SomeDerived<NT>> bindFunc);
}

public delegate AnotherDerived<T2> bindee<in T1, out T2, out AnotherDerived>(T1 param)
    where AnotherDerived<T2> : GenericInterface<T2, AnotherDerived>;

public class Derived<T> : GenericInterface<T, Derived>
{
    Derived<NT> bind<NT>(bindee<T, NT, Derived<NT>> bindFunc);
}

但它无法编译,我收到此错误:

  

无效令牌'&lt;'在类,结构或接口成员声明中

在这种情况下,正确的设计是什么?

编辑:

我理解编译器错误的合成原因。您不能在where子句中将泛型类型参数应用于参数。 我在问模仿这种行为的最佳方式是什么。

1 个答案:

答案 0 :(得分:2)

我会在这里说清楚你要用Generic做什么是不可能的;如果有人认为我错了,我会删除。

让我们从这个开始

interface IFoo<T> where T : IFoo<T>{}
class Foo<T> : IFoo<T> where T : IFoo<T>{}
class Bar<T> : Foo<T> where T : IFoo<T>{}

让我们尝试实现这个目标;

var foo = new Foo< Bar< ....errr what now? ad infinitum... 

所以要解决这个问题,你需要重新设计,这样你的课程看起来更像是这样:

interface IBase {}
interface IFoo<out T> where T : IBase { }
class Foo<T> : IFoo<T> where T : IBase { }

然后允许:

IFoo<IBase> foo = new Foo<Base>();

[附录]

你可以使用功能级泛型,让你解决这些问题......

interface IFoo<out T> where T : IBase
{
    IFoo<TBind> Bind<TBind>(Action<T, TBind> bindFunc) where TBind : IBase;
}