解决Linq.Expressions.NewExpression?
Resolve Linq.Expressions.NewExpression?
如何 'compile' NewExpression
实例化指向的 new
表达式?
我是否必须手动构建对象,或者我可以将构建的对象作为参数获取?
很快就会用一个例子来更新我的问题。
class Obj
{
public async Task ParseAsync<TObj>(Expression<Func<TObj, Task>> pointedMethod)
{
var method = pointedMethod.Body as MethodCallExpression;
var arg = method.Arguments[0];
var newExp = arg as NewExpression;
//This is what I need:
User = newExp.ConstructObject();
await Task.FromResult((object)null);
}
public async Task MyMethod(User user)
{
await Task.FromResult((object)null);
}
}
static void Main(string[] args)
{
var obj = new Obj();
obj.ParseAsync<Obj>(o => o.MyMethod(new User())).Wait();
}
备注:
在执行时,不会有对 TObj
的正确引用,必须仅根据提供给 ParseAsync
函数的参数构造项目。
由于我有一个 NewExpression
,这意味着该对象(在我的示例中为 User
)能够被构造。
问题是是否有一种方法可以实例化对象而无需手动查找构造函数并调用它等
答案最初由@dasblinkenlight回答,我不知道他为什么删除它,它只是有效。无论如何,如果他选择取消删除他的回答,我会删除我的并归功于他!
总之供参考:
The answer depends on whether or not the NewExpression in question
references any parameters, and if you have access to these parameter
expressions in case it does.
If NewExpression has no parameters, simply construct a lambda
expression from it, compile, and run:
NewExpression myNewExpression = ... // You have this
var instantiator = (Func<MyResultType>)Expression
.Lambda<Func<MyResultType>>(myNewExpression)
.Compile();
MyResultType res = instantiator();
如何 'compile' NewExpression
实例化指向的 new
表达式?
我是否必须手动构建对象,或者我可以将构建的对象作为参数获取?
很快就会用一个例子来更新我的问题。
class Obj
{
public async Task ParseAsync<TObj>(Expression<Func<TObj, Task>> pointedMethod)
{
var method = pointedMethod.Body as MethodCallExpression;
var arg = method.Arguments[0];
var newExp = arg as NewExpression;
//This is what I need:
User = newExp.ConstructObject();
await Task.FromResult((object)null);
}
public async Task MyMethod(User user)
{
await Task.FromResult((object)null);
}
}
static void Main(string[] args)
{
var obj = new Obj();
obj.ParseAsync<Obj>(o => o.MyMethod(new User())).Wait();
}
备注:
在执行时,不会有对 TObj
的正确引用,必须仅根据提供给 ParseAsync
函数的参数构造项目。
由于我有一个 NewExpression
,这意味着该对象(在我的示例中为 User
)能够被构造。
问题是是否有一种方法可以实例化对象而无需手动查找构造函数并调用它等
答案最初由@dasblinkenlight回答,我不知道他为什么删除它,它只是有效。无论如何,如果他选择取消删除他的回答,我会删除我的并归功于他!
总之供参考:
The answer depends on whether or not the NewExpression in question references any parameters, and if you have access to these parameter expressions in case it does.
If NewExpression has no parameters, simply construct a lambda expression from it, compile, and run:
NewExpression myNewExpression = ... // You have this var instantiator = (Func<MyResultType>)Expression .Lambda<Func<MyResultType>>(myNewExpression) .Compile(); MyResultType res = instantiator();