How to create a Expression.Lambda when a type is not known until runtime?

后端 未结 3 1931
南方客
南方客 2020-12-14 10:19

This is best explained using code. I have a generic class that has a method that returns an integer. Here is a simple version for the purposes of explaining...



        
3条回答
  •  一生所求
    2020-12-14 10:45

    This answer only applies if you are using .NET 4.0.

    If you make genericInstance dynamic instead of object, you can then call the DoSomething method on it directly, and the dynamic language runtime will take care of everything for you.

    class Type1 {
        public int DoSomething() { return 1; }
    }
    class Type2 {
        public int DoSomething() { return 2; }
    }
    
    static void TestDynamic() {
        dynamic t1 = Activator.CreateInstance(typeof(Type1));
        int answer1 = t1.DoSomething(); // returns 1
    
        dynamic t2 = Activator.CreateInstance(typeof(Type2));
        int answer2 = t2.DoSomething(); // returns 2
    }
    

    If you need to keep this class structure (Gen), then I don't see an easy way around the fact that you don't know the type T at compile time. If you want to call the delegate, you either have to know its full type at compile time, or you need to pass in the parameters as objects.

    Using dynamic gets you to hide the complexity of getting the MethodInfo, etc., and gives you excellent performance. The one drawback vs. DynamicInvoke that I see is that I believe you get the initial overhead of resolving the dynamic call once for every call site. The bindings are cached so that they run very fast from the second time onwards if you call it on objects with the same type.

提交回复
热议问题