当我只有泛型类型和实例值时,如何手动构建表达式树?
我有一个如下所示的通用类:
public class MyClass<T, TProperty>
{
MyClass(Expression<Func<T, TProperty>> expression)
{
}
}
就我而言,我想使用 Activator 动态创建该类的实例。所以我需要的是为构造函数创建一个表达式。我拥有的是类型(System.Type)和对象(System.Object),我想要如下所示的内容:
Expression<Func<T, TProperty>> exp = x => someValue;
“someValue”被声明为对象,但它的真实类型绝对是TProperty。它是通过反射解决的,所以这里的类型是object。
问题是类型 T 和 TProperty 将是通用的,我直到运行时才知道类型,所以我无法将“someValue”转换为 TProperty。我们拥有的是 typeof(T)、typeof(TProperty) 和一个对象 -,-
I have a generic class like below:
public class MyClass<T, TProperty>
{
MyClass(Expression<Func<T, TProperty>> expression)
{
}
}
In my case, I want to dynamically create an instance of that class using Activator. So what I need is to create an expression for the constructor. What I have are the types (System.Type) and an object (System.Object) and I want something like below:
Expression<Func<T, TProperty>> exp = x => someValue;
"someValue" is declared as object but it's real type is definitely TProperty. It's resolved by reflection so the type here is object.
The problem is that the type T and TProperty will be generic, I don't know the types until run-time so I can't cast "someValue" to TProperty. What we have are typeof(T), typeof(TProperty) and an object -,-
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我想我明白这个问题了。
给定示例输入:
您想要创建相当于以下内容的代码:
以下是您可以做到这一点的方法。
首先,创建表达式树:
然后使用反射创建
MyClass
实例:Ok, I think I understand the question.
Given sample input:
You want to create code equivalent to:
Here's how you can do that.
First, create the expression-tree:
And then use reflection to create the
MyClass<T, TProperty>
instance: