I have a method and two delegate like below. It is running in this way. But I want to use Delegate.CreateInstance. The types of the dx and the dy must be Func<IEnumerable<Foo>>. Like below the fx and fy. They must not be Func<int, IEnumerable<Foo>>.
public class Test {
private IEnumerable<T> CreateItems<T>(int count) where T : class
{
for (int i = 0; i < count; i++)
{
yield return (T)Activator.CreateInstance(typeof(T), i.ToString());
}
}
public List<T> TestMethod<T>(int i = 1) where T : class
{
return CreateItems<T>(i).ToList();
}
public void TestRun()
{
const int Count = 5;
Func<IEnumerable<Foo>> fx = () => this.TestMethod<Foo>(Count);
Func<IEnumerable<Foo>> fy = () => this.TestMethod<Foo>();
var lfx = fx.Invoke();
var lfy = fy.Invoke();
var dx = Delegate.CreateDelegate( ?? );
var dy = Delegate.CreateDelegate( ?? );
var ldx = dx.DynamicInvoke();
var ldy = dy.DynamicInvoke();
}
}
If you want the type to be
Func<IEnumerable<Foo>>, then you cannot create that directly viaDelegate.CreateDelegatesince they require two parameters: the instance (akathis), and the integeri. Even the form shown infxhas ani– it just happens to be supplied by the compiler. IfTestMethoddidn’t take parameters, it could be done via:To do this (partial application) dynamically, you would need to create a type that has the instance (
this), the value to inject (thei), and a method that callsTestMethod<Foo>with those values. Which is exactly what the compiler does for you here:That basically creates:
and: