p.anotherentity.fieldname.-6ren">
gpt4 book ai didi

c# - 我如何扩展这个表达式?

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:49 25 4
gpt4 key购买 nike

我以这段代码为例,基本就吐出来了

p => p.fieldname.StartsWith("123")

但是我会扩展到谁来做这样的事情:

p => p.anotherentity.fieldname.StartsWith("123")

这是我根据自己的需要重构的代码示例:

string propertyName = "FirstName";
string methodName = "StartsWith";
string keyword = "123";

Type t = typeof (Person);

ParameterExpression paramExp = Expression.Parameter(t, "p");
// the parameter: p

MemberExpression memberExp = Expression.MakeMemberAccess(paramExp,
t.GetMember(propertyName).FirstOrDefault());
// part of the body: p.FirstName

MethodCallExpression callExp = Expression.Call(memberExp,
typeof (string).GetMethod(methodName,
new Type[] {typeof (string)}),
Expression.Constant(keyword));
// the body: p.FirstName.StartsWith("123")

Expression<Func<Person, bool>> whereExp = Expression.Lambda<Func<Person, bool>>(callExp, paramExp);
Expression<Func<Person, string>> selectExp = Expression.Lambda<Func<Person, string>>(memberExp, paramExp);

Console.WriteLine(whereExp); // p => p.FirstName.StartsWith("123")
Console.WriteLine(selectExp); // p => p.FirstName

为了进一步解释,让我告诉你我想做什么:

public class Person 
{
public string IdentityCode {get;set;}
public Loans Loans {get;set;}
}

public class Loans
{
public int Id {get;set;}
public Asset Assets {get;set;}
public Person person {get;set;}
}

public class Asset
{
public string SerialNumber {get;set;}
}

然后使用表达式构建如下内容:

p => p.Loans.Asset.SerialNumber.StartsWith("123)

或者

p => p.Loans.Person.IdentityCode.StartsWith("123")

最佳答案

未经测试,但是...

ParameterExpression paramExp = Expression.Parameter(t, "p"); // the parameter: p

MemberExpression memberExp =
Expression.MakeMemberAccess(paramExp, t.GetMember(propertyName).FirstOrDefault());

会变成这样:

ParameterExpression paramExp = Expression.Parameter(t, "p"); // the parameter: p

MemberExpression otherEntityExp =
Expression.MakeMemberAccess(paramExp, t.GetMember("anotherentity").FirstOrDefault());

MemberExpression memberExp =
Expression.MakeMemberAccess(otherEntityExp, t.GetMember(propertyName).FirstOrDefault());

关于c# - 我如何扩展这个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com