我正在尝试将委托类型作为类型参数传递,以便稍后我可以在代码中将其用作类型参数,如下所示:
// 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); }
原文地址:https://www.jb51.cc/csharp/100596.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。