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.CreateDelegate
since they require two parameters: the instance (akathis
), and the integeri
. Even the form shown infx
has ani
- it just happens to be supplied by the compiler. IfTestMethod
didn'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:
That's impossible. There is no way you can fit an instance method with signature
A F(X x)
into aFunc<A>
directly.It's possible to bind the first parameter of a method into the delegate directly, but no additional parameters. In your case the instance
this
is that first parameter, and you can't bind a value fori
.I guess your misunderstanding is how parameters with default values work. They're still parameters that need to be filled in by the caller. It's just that the C# compiler does that for you.
You will need a wrapper of some kind with the correct signature. That can be a lambda, or some other helper method. In your case I'd overload the method
TestMethod
instead of using a default parameter.