我试图在@Marc Gravell概述的this question中实施解决方案。但是,我很难将MemberInfo
投射到MethodInfo
。我正在使用.NET 4.7,并使用CodeDOM
进行一些时髦的动态编译。我怀疑RtFieldInfo
->
MethodInfo
转换是由于它是一个静态类/静态成员,或,我正在做一些愚蠢的事情compilationwise。
一切都有帮助,谢谢!
static void Main(string[] args)
{
string code = @"
using System;
using System.IO;
namespace MyProgram.DynamicallyCompiled
{
public static class Functions
{
// just a proof-of-concept dummy function.
public static Func<object, Func<FileInfo, bool>> _func_Axnflzhh =
o => f => {
var i = o.GetHashCode();
return o.GetHashCode() > f.GetHashCode();
};
}
}
";
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
Type type = results.CompiledAssembly.GetType("MyProgram.DynamicallyCompiled.Functions");
MemberInfo mi = type.GetMember("_func_Axnflzhh")[0];
Func<object,Func<FileInfo, bool>> f = Delegate.CreateDelegate(
typeof(Func<object,Func<FileInfo, bool>>), (MethodInfo)mi);
// System.InvalidCastException: 'Unable to cast object of type 'System.Reflection.RtFieldInfo' to type 'System.Reflection.MethodInfo'.'
}