【问题标题】:Partially applying generics for type constraints对类型约束部分应用泛型
【发布时间】:2013-09-14 21:08:31
【问题描述】:

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

我尝试了以下方法:

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);
}

但是编译失败,我得到这个错误:

类、结构或接口成员声明中的标记“

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

编辑:

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

【问题讨论】:

  • 你能告诉我们那个 weird 错误 - 完整和完整的错误以及所有细节。
  • 好吧,也许奇怪不是正确的术语......编译器不喜欢在“where”规范中有
  • 类、结构或接口成员声明中的标记“”无效;类、结构或接口成员声明中的标记“{”无效;语法错误,应为“:”
  • 好的,现在请告诉 exactly WHERE 在您的代码中您遇到了这个错误!
  • 我同意marc_s,问题必须描述具体问题

标签: c# generics contravariance type-constraints


【解决方案1】:

我会在这里冒昧地说你想用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多