当类型仅在运行时已知时,如何使用表达式树调用泛型方法?
这是我使用反射解决的问题,但想看看如何使用表达式树来解决这个问题。
我有一个通用函数:
private void DoSomeThing<T>( param object[] args ) {
// Some work is done here.
}
我需要从班级的其他地方调用它。现在,通常情况下,这很简单:
DoSomeThing<int>( blah );
但前提是我在设计时知道我正在使用 int
。当我直到运行时才知道类型时,我需要帮助。就像我说的,我知道如何通过反射来做到这一点,但我想通过表达式树来做到这一点,因为我(非常有限)的理解是我可以这样做。
有什么建议或指向可以让我了解这一点的网站吗?最好有示例代码?
This is something that I solved using reflection, but would like to see how to do it using expression trees.
I have a generic function:
private void DoSomeThing<T>( param object[] args ) {
// Some work is done here.
}
that I need to call from else where in my class. Now, normally, this would be be simple:
DoSomeThing<int>( blah );
but only if I know, at design time that I am working with an int
. When I do not know the type until runtime is where I need the help. Like I said, I know how to do it via reflection, but I would like to do it via expression trees, as my (very limited) understanding is that I can do so.
Any suggestions or points to sites where I can get this understanding, preferably with sample code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,可以通过表达式树来完成。优点是您可以获得委托,因此重复调用将比一遍又一遍地执行
MethodInfo.Invoke()
快得多。dynamic
关键字也可以做到这一点。示例:
代码:
Yes, it can be done via expression trees. The advantage is that you get a delegate so repeated calls will be far faster than doing
MethodInfo.Invoke()
over and over again. Thedynamic
keyword can do this also.Example:
Code:
MethodInfo.MakeGenericMethod
然后创建委托并调用它。(当然不是在表达式中;p)更新:
一般来说,我更喜欢为此使用泛型类型,
Activator.CreateInstance
只需要更少的工作。不过,一切都取决于您的情况。MethodInfo.MakeGenericMethod
Then just create a delegate and call it.(not in an expression, of course ;p)Update:
Generally, I prefer to use generic types for this,
Activator.CreateInstance
just requires less work. All depends on your situation though.