I am convinced that it is impossible to do exactly what you want on .NET 3.5.
The only way that comes close is not using lambda, but simple old methods. Essentially, you would define your actions in a class like the following:
public class FooActionMethods<TFoo> { public static void DoSomething(TFoo foo) { int i = 0; int number = (int)typeof(TFoo).GetMethod("GetNumber").Invoke(foo, null); Console.WriteLine(i + number); } }
Then you can call, for example, the DoSomething method:
Type fooType = // somehow, we get the type from other assembly object fooInstance = Activator.CreateInstance(fooType); Type fooActionType = typeof(Action<>).MakeGenericType(fooType); Type fooActionMethodsType = typeof(FooActionMethods<>).MakeGenericType(fooType); Delegate action = Delegate.CreateDelegate(fooActionType, fooActionMethodsType, "DoSomething"); fooType.GetMethod("UseFoo").Invoke(fooInstance, new object[] { action });
Since the entire FooActionMethod class is shared, we can use reflection ( MakeGenericType ) and create a private FooActionMethod with the exact type Foo . Since at compile time we do not have information about TFoo , we can only interact with our instances through reflection. To simplify these interactions, check out the SO question , which concerns some libraries that would make it easier to work with reflection.
Other than that, I think you can’t do anything. Thanks for the good question - makes a great puzzle! :)
Just like a side effect, I also tried to solve this using expression trees to dynamically create a lambda expression. I could not find a way to enable closures with expression trees. Otherwise, this method will work fine.
source share