lundi 5 mars 2018

MemberInfo to Func

I have attempted to implement the solution in this question outlined by @Marc Gravell. I am having difficulty getting a MemberInfo to cast to a MethodInfo, however. I am using .NET 4.7, and doing some funky dynamic compilation using CodeDOM. I suspect the RtFieldInfo -> MethodInfo conversion is due to either the fact that it is a static class/static member, or that I'm doing something goofy compilationwise.

Anything helps, thanks!

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'.'

    }





Aucun commentaire:

Enregistrer un commentaire