c# – 将委托作为类型参数传递并使用它会引发错误CS0314
发布时间:2020-12-15 17:15:24 所属栏目:百科 来源:网络整理
导读:我正在尝试将委托类型作为类型参数传递,以便稍后我可以在代码中将其用作类型参数,如下所示: // Definitionprivate static class Register{ public static FunctionObject CreateT(CSharp.Context c,T func) { return new IronJS.HostFunctionT(c.Environmen
我正在尝试将委托类型作为类型参数传递,以便稍后我可以在代码中将其用作类型参数,如下所示:
// Definition private static class Register { public static FunctionObject Create<T>(CSharp.Context c,T func) { return new IronJS.HostFunction<T>(c.Environment,func,null); } } // Usage Register.Create<Func<string,IronJS.CommonObject>>(c,this.Require); 但是,C#编译器抱怨: The type 'T' cannot be used as type parameter 'a' in the generic type or method 'IronJS.HostFunction<a>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.Delegate'." 我试图通过在函数中附加“where T:System.Delegate”来解决这个问题,但是,你不能使用System.Delegate作为类型参数的限制: Constraint cannot be special class 'System.Delegate' 有谁知道如何解决这个冲突? 不工作(在演员表中参数和返回类型信息丢失): Delegate d = (Delegate)(object)(T)func; return new IronJS.HostFunction<Delegate>(c.Environment,d,null); 解决方法
如果你看一下
https://github.com/fholm/IronJS/blob/master/Src/IronJS/Runtime.fs,你会看到:
and [<AllowNullLiteral>] HostFunction<'a when 'a :> Delegate> = inherit FO val mutable Delegate : 'a new (env:Env,delegateFunction,metaData) = { inherit FO(env,metaData,env.Maps.Function) Delegate = delegateFunction } 换句话说,您不能使用C#或VB来编写函数,因为它需要使用System.Delegate作为类型约束.我建议您在F#中编写函数或使用反射,如下所示: public static FunctionObject Create<T>(CSharp.Context c,T func) { // return new IronJS.HostFunction<T>(c.Environment,null); return (FunctionObject) Activator.CreateInstance( typeof(IronJS.Api.HostFunction<>).MakeGenericType(T),c.Environment,null); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |