我完全在这一个丢失。我有一张code,做我需要在这样的实施是什么:
I am completely lost on this one. I have a piece of code that does what I need when implemented like this:
return filters.Add(m => m.Metadata.RecordId).IsEqualTo(1);
其中m为 TestObj
类对象和添加
方法的参数是防爆pression< Func键< TestObj,布尔>>
where m is a TestObj
class object and Add
method's argument is Expression<Func<TestObj,bool?>>
.
现在的问题是,我不能硬code m.Metadata.RecordId里面添加的,因为我来到这里就是告诉我有关应使用属性的字符串,在这种情况下,Metadata.RecordId 。我需要做的就是构建这样一个前pression这个字符串,会做同样的事情为m => m.Metadata.RecordId一样。我需要的是这样的:
Now the problem is that I cannot hardcode m.Metadata.RecordId inside Add, because what I get here is a string that informs me about the property that should be used, in this case "Metadata.RecordId". what I need to do is to construct such an expression with this string that will do the same thing as m => m.Metadata.RecordId does. I need something like this:
string propertyName = "Metadata.RecordId";
Expression expr = null;//create expression here somehow that will do the same as m => m.Metadata.RecordId
return filters.Add(expr).IsEqualTo(1);
我该怎么办呢?
How do I do that?
我不知道究竟你想有作为输出(BOOL,INT和比较), 但是,这应该让你在正确的轨道......
I'm not sure what exactly you want there as an output (bool, int and comparing), But this should get you on the right track...
public static void Test(string propertyPath)
{
var props = propertyPath.Split('.');
Expression parameter = Expression.Parameter(typeof(TestObj), "x");
Expression property = parameter;
foreach (var propertyName in props)
property = Expression.Property(property, propertyName);
Expression<Func<TestObj, int>> lambdaExpression =
Expression.Lambda<Func<TestObj, int>>(property, parameter as ParameterExpression);
Add(lambdaExpression);
}
static void Add(Expression<Func<TestObj, int>> paramExp)
{
TestObj obj = new TestObj { Metadata = new Metadata { RecordId = 1, Name = "test" } };
var id = paramExp.Compile()(obj);
}
和您还可以查看这个帖子Jon的这很好地描述了如何工作的? Use反射来获取物业名称拉姆达EX pression
And you can also check this post of Jon's which nicely describes how that works... Use reflection to get lambda expression from property Name