Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对类型约束部分应用泛型_C#_Generics_Contravariance_Type Constraints - Fatal编程技术网

C# 对类型约束部分应用泛型

C# 对类型约束部分应用泛型,c#,generics,contravariance,type-constraints,C#,Generics,Contravariance,Type Constraints,我目前试图构造一个泛型接口,使派生它的每个(泛型)类都有一个接受委托的方法,该委托接受类型参数并返回同一类型的另一个类,但只返回另一个类型参数 我尝试了以下方法: public interface GenericInterface<out T, out SomeDerived> where SomeDerived<T> : GenericInterface<T, SomeDerived> { SomeDerived<NT> bind

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

我尝试了以下方法:

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);
}
公共接口通用接口
其中:泛型接口
{
somederivebind(bindee-bindFunc);
}
公共委托另一个派生的绑定对象(T1参数)
其中另一个派生:通用接口;
派生的公共类:GenericInterface
{
派生绑定(bindee-bindFunc);
}
但它无法编译,我得到了以下错误:


无效标记“我将在这里断章取义地说,你在这里试图用泛型做什么是不可能的;如果有人认为我错了,我就撤职

让我们从这个开始

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>{}
接口IFoo,其中T:IFoo{}
类Foo:IFoo其中T:IFoo{}
类栏:Foo其中T:IFoo{}
让我们试着举例说明这一点

var foo = new Foo< Bar< ....errr what now? ad infinitum... 
var foo=new foo
要解决这个问题,您需要重新设计,使您的类看起来更像这样:

interface IBase {}
interface IFoo<out T> where T : IBase { }
class Foo<T> : IFoo<T> where T : IBase { }
接口IBase{}
接口IFoo,其中T:IBase{}
类Foo:IFoo其中T:IBase{}
然后允许:

IFoo<IBase> foo = new Foo<Base>();
ifoofoo=newfoo();
[增编]

您可以使用函数级泛型来解决以下问题

interface IFoo<out T> where T : IBase
{
    IFoo<TBind> Bind<TBind>(Action<T, TBind> bindFunc) where TBind : IBase;
}
接口IFoo,其中T:IBase
{
IFoo绑定(Action bindFunc),其中TBind:IBase;
}

你能告诉我们那个奇怪的错误吗?请告诉我们所有细节的完整错误。也许奇怪不是正确的术语。。。编译器不喜欢在类、结构或接口成员声明中的“where”规范中包含无效令牌“”;类、结构或接口成员声明中的无效标记“{”;语法错误“:”expectedOK,现在还请确切地告诉代码中出现此错误的位置!我同意marc_的观点,问题必须描述具体问题