System.Runtime.CompilerServices 在 .NET 标准库中

System.Runtime.CompilerServices in .NET Standard library

目前我正在将 .NET 4.5 class 库转换为 .NET Core class 库,引用 .NETStandard v1.6.

在我的部分代码中(严重依赖反射)我需要确定一个对象是否属于 Closure 类型,它位于 System.Runtime.CompilerServices 命名空间中。此命名空间和类型在 .NETStandard v1.6.

中不可用

依赖Closure的具体代码决定委托的参数类型,跳过编译器生成的Closure个。

Delegate toWrap;
MethodInfo toWrapInfo = toWrap.GetMethodInfo();
var toWrapArguments = toWrapInfo.GetParameters()
    // Closure argument isn't an actual argument, but added by the compiler.
   .SkipWhile( p => p.ParameterType == typeof( Closure ) )
   .Select( p => p.ParameterType );

在 .Net Core 1.0 中,Closure exists in the System.Linq.Expressions assembly in the System.Linq.Expressions package,但它没有在参考程序集中公开。这意味着它只是 Core 中的一个实现细节(例如,可能会在未来的版本中消失或移动)。这也意味着您不能在编译时引用它(就像您在 .Net Framework 中所做的那样),但您可以在运行时使用反射检索它(不要忘记 using System.Reflection; for GetTypeInfo()):

Type closureType = typeof(Expression).GetTypeInfo().Assembly
    .GetType("System.Runtime.CompilerServices.Closure");

在 .Net Framework 中,Closure 位于不同的程序集中(即 System.Core),但 Expression 也是如此,因此此代码应该适用于两者。