gpt4 book ai didi

c# - 获取作为 lambda 表达式传递的参数的 PropertyInfo

转载 作者:太空狗 更新时间:2023-10-29 17:29:00 24 4
gpt4 key购买 nike

比如我有一个类:

public class Person
{
public int Id;
public string Name, Address;
}

并且我想调用一个方法来根据 Id 更新此类中的信息:

update(myId, myPerson => myPerson.Name = "abc");

解释:这个方法会从数据库中查询并得到Person实体给定一个myId,然后它设置Name为“abc”,所以它的作用与我所说的相同:

update(myId, myPerson => myPerson.Address = "my address");

这可能吗?如果是怎么办?

最佳答案

我不会使用 PropertyInfo,就像 Reed Copsey 在他的回答中所说的那样,但仅供引用,您可以提取 PropertyInfo的表达式:

public PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
{
MemberExpression Exp = null;

//this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
if (GetPropertyLambda.Body is UnaryExpression)
{
var UnExp = (UnaryExpression)GetPropertyLambda.Body;
if (UnExp.Operand is MemberExpression)
{
Exp = (MemberExpression)UnExp.Operand;
}
else
throw new ArgumentException();
}
else if (GetPropertyLambda.Body is MemberExpression)
{
Exp = (MemberExpression)GetPropertyLambda.Body;
}
else
{
throw new ArgumentException();
}

return (PropertyInfo)Exp.Member;
}

对于像 MyPerson.PersonData.PersonID 这样的复合表达式,您可以获取子表达式,直到它们不再是 MemberExpressions

public PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
{
//same body of above method without the return line.
//....
//....
//....

var Result = (PropertyInfo)Exp.Member;

var Sub = Exp.Expression;

while (Sub is MemberExpression)
{
Exp = (MemberExpression)Sub;
Result = (PropertyInfo)Exp.Member;
Sub = Exp.Expression;
}

return Result;
//beware, this will return the last property in the expression.
//when using GetValue and SetValue, the object needed will not be
//the first object in the expression, but the one prior to the last.
//To use those methods with the first object, you will need to keep
//track of all properties in all member expressions above and do
//some recursive Get/Set following the sequence of the expression.
}

关于c# - 获取作为 lambda 表达式传递的参数的 PropertyInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115634/

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