使用反射调用静态泛型方法传递 Lamba 作为参数
是否可以通过反射编写以下代码?
var fake = A.Fake<Foo>(
o => o.WithArgumentsForConstructor(new[] { "Hello" }));
其中 o 是:
Action<IFakeOptionsBuilder<T>>
其中 WithArgumentsForConstructor 是:
IFakeOptionsBuilder<T> WithArgumentsForConstructor(IEnumerable<object> argumentsForConstructor);
Foo 类是:
class Foo
{
public Foo(string s)
{
}
}
我所做的是:
object fake = typeof(A)
.GetMethod("Fake", new Type[] { })
.MakeGenericMethod(new[] { this.targetType })
.Invoke(null, /* Here I need to pass the lambda. */);
Is it possible to write the following code via Reflection?
var fake = A.Fake<Foo>(
o => o.WithArgumentsForConstructor(new[] { "Hello" }));
Where o is:
Action<IFakeOptionsBuilder<T>>
Where WithArgumentsForConstructor is:
IFakeOptionsBuilder<T> WithArgumentsForConstructor(IEnumerable<object> argumentsForConstructor);
The Foo class is:
class Foo
{
public Foo(string s)
{
}
}
What I did was:
object fake = typeof(A)
.GetMethod("Fake", new Type[] { })
.MakeGenericMethod(new[] { this.targetType })
.Invoke(null, /* Here I need to pass the lambda. */);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,可以通过反思来做你建议的事情,但完全没有必要。自己定义一个静态方法会更简单,如下所示:
现在只需使用反射调用此函数:
Yes, it is possible to do what you suggest via reflection, however quite unnecessary. It would be simpler to define a static method yourself like this:
Now simply call this function using reflection:
如果我正确理解了这个问题,那么以下应该没问题:
With
Foo
defied as:If I've understood the question correctly, the following should be fine:
With
Foo
defied as:最后! :)
困难的部分是,在运行时,我不知道类型,因此泛型不是一个选项(甚至在私有帮助器方法上也是如此)。
场景是能够做到这一点:
这是我得到的解决方案:
像魅力一样工作。 :)
Finally! :)
The difficult part was that, on runtime, I don't know the types so generics is not an option (not even on the private helper method).
The scenario is to be able to do this:
Here is the solution I got:
Works like a Charm. :)