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

Jun*_*des 8 .net c# delegates .net-3.5

我正在尝试将委托类型作为类型参数传递,以便我可以稍后在代码中将其用作类型参数,如下所示:

// 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);
Run Code Online (Sandbox Code Playgroud)

但是,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'."
Run Code Online (Sandbox Code Playgroud)

我试图通过在函数中附加"where T:System.Delegate"来解决这个问题,但是,你不能使用System.Delegate作为类型参数的限制:

Constraint cannot be special class 'System.Delegate'
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个冲突?

不工作(在演员表中参数和返回类型信息丢失):

Delegate d = (Delegate)(object)(T)func;
return new IronJS.HostFunction<Delegate>(c.Environment, d, null);
Run Code Online (Sandbox Code Playgroud)

Gab*_*abe 6

如果你看一下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
  }
Run Code Online (Sandbox Code Playgroud)

换句话说,您不能使用C#或VB来编写函数,因为它需要使用System.Delegate作为类型约束.我建议您使用F#编写函数或使用反射,如下所示:

public static FunctionObject Create<T>(CSharp.Context c, T func)
{
  // return new IronJS.HostFunction<T>(c.Environment, func, null);
  return (FunctionObject) Activator.CreateInstance(
    typeof(IronJS.Api.HostFunction<>).MakeGenericType(T),
    c.Environment, func, null);
}   
Run Code Online (Sandbox Code Playgroud)