0

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

    }
Ian Ray
  • 117
  • 4
  • It's a field, not a method (or property). You can't create a delegate from a field directly like that. – Jeff Mercado Mar 05 '18 at 22:36
  • Ah! Thank you, Jeff. If that is the case, it would seem that the only way to access the Func again after compilation would be to get the instance of Func out from the FieldInfo as an `object` via the GetValue method, and then cast it with type arguments hardcoded? No way to get a MethodInfo out of this guy? – Ian Ray Mar 05 '18 at 22:39
  • `_func_Axnflzhh` is a field that happens to hold an instance of a lambda. If you want to expose that lambda instance as a delegate, you just need to get the value of that field. There's no method to read from. – Jeff Mercado Mar 05 '18 at 22:44

0 Answers0