将委托作为类型参数传递并使用它会引发错误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,func,null);
  return (FunctionObject) Activator.CreateInstance(
    typeof(IronJS.Api.HostFunction<>).MakeGenericType(T),c.Environment,null);
}   
    ,        @Gabe是完全正确的,它与HostFunction <\'a>类上的类型约束有关,该类约束仅在F#(而不是C#或VB)中有效。 您是否检查了Native.Utils中的功能?这就是我们在运行时内部使用的从委托创建函数的方法。尤其是
let CreateFunction (env:Env) (length:Nullable<int>) (func:\'a when \'a :> Delegate) =
函数应该可以完全满足您的需求。 如果CreateFunction无法满足您的需求,请在http://github.com/fholm/IronJS/issues上打开票证,其中列出了您所缺少的内容以及您希望如何实现它以及我们我会正确的。     ,        作为2018年5月之后阅读此内容的任何人的更新: 从c#7.3(.Net Framework 4.7.2)开始,现在可以使用ѭ8作为通用声明的约束,这意味着原始发布者现在可以执行她在c#中试图做的事情-而无需必须诉诸于使用另一种.Net语言构建类。
System.Enum
(较早的c#版本中的另一个严重缺失的约束)现在也可用。还有其他一些附加功能。 https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#delegate-constraints