用c#中的反射创建表达式方法 [英] create Expression method with reflection in c#
本文介绍了用c#中的反射创建表达式方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我想要的:
This is what I want to make:
output.Where(d => d.JN_NewsCategories.NewsCategoriesEn.Contains("event"));
d是模型。我的型号名称是JN_News
我开始编写代码:
d is a Model. my model name is JN_News
I start to write code :
var modelName = "JN_News";
var subModelName = "JN_NewsCategories";
var subModelField = "NewsCategoriesEn";
var splitSeacrh="event";
Type modelClass = GetModel(modelName);
ParameterExpression peSubModel = Expression.Parameter(modelClass, "x");
//Note this line:
Expression left= Expression.Property(peSubModel, modelClass.GetProperty(subModelName));
// left= x.JN_NewsCategories
//How do I access the field. Like this : x.JN_NewsCategories.NewsCategoriesEn
// I tried very hard but did not succeed
Expression right= Expression.Constant(splitSeacrh);
MethodCallExpression conditionExpressionSubModel = Expression.Call(left,
typeof(string).GetMethod("Contains"), right);
推荐答案
这是你想要的吗?
Is this you want?
var modelName = "JN_News";
var subModelName = "JN_NewsCategories";
var subModelField = "NewsCategoriesEn";
var splitSeacrh = "event";
Type modelClass = GetModel(modelName);
ParameterExpression peSubModel = Expression.Parameter(modelClass, "x");
Expression left = Expression.Property(peSubModel, modelClass.GetProperty(subModelName));
left = Expression.Field(left, modelClass.GetProperty(subModelName).PropertyType.GetField(subModelField));
Expression right = Expression.Constant(splitSeacrh, typeof(string));
MethodCallExpression conditionExpressionSubModel = Expression.Call(left,
typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), right);
在我的想象中,你的模型应如下所示:
In my imagination,your models should look like this:
class JN_News
{
public Categories JN_NewsCategories { get; set; }
}
class Categories
{
public string NewsCategoriesEn = "eventForSomething";
}
这篇关于用c#中的反射创建表达式方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文