我正在尝试将委托类型作为类型参数传递,以便稍后我可以在代码中将其用作类型参数,如下所示:
// 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);
}