c# – 将委托作为类型参数传递并使用它会引发错误CS0314

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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...