我有一个方法和两个委托,如下所示。它就是这样运行的。但我想使用Delegate.CreateInstance。 dx 和 dy 的类型必须是Func<IEnumerable<Foo>>
。就像下面的 fx 和 fy 一样。他们一定不能是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();
}
}
如果你想要的类型是Func<IEnumerable<Foo>>
,那么你就无法创建它directly via Delegate.CreateDelegate
因为它们需要两个参数:实例(又名this
) 和整数i
。甚至如图所示的形式fx
has an i
- 它恰好是由编译器提供的。如果TestMethod
不带参数,可以通过以下方式完成:
var dy = (Func<IEnumerable<Foo>>) Delegate.CreateDelegate(
typeof(Func<IEnumerable<Foo>>),
this,
GetType().GetMethod("TestMethod").MakeGenericMethod(typeof(Foo))
);
要动态地执行此操作(部分应用程序),您需要创建一个具有实例的类型(this
),要注入的值(i
),以及一种方法calls TestMethod<Foo>
与这些价值观。这是exactly编译器在这里为你做了什么:
Func<IEnumerable<Foo>> fx = () => this.TestMethod<Foo>(Count);
这基本上创建了:
internal class <>_squiggle {
public Test @this;
public IEnumerable<Foo> Method() {
return @this.TestMethod<Foo>(5);
}
}
and:
var capture = new <>_squiggle { @this = this };
var fx = new Func<IEnumerable<Foo>>(capture.Method);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)