gpt4 book ai didi

foreach 循环中的 C# Expression.PropertyOrField

转载 作者:行者123 更新时间:2023-11-30 23:04:20 24 4
gpt4 key购买 nike

我正在尝试通过字符串数组获取给定类的第一级属性的表达式,每个字符串都与属性名称相关以获取表达式:

public List<MemberExpression> CreateMembers(string propertyPaths)
{
List<MemberExpression> test = new List<MemberExpression>();



var propertiesPath = propertyPaths.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

foreach (var propertyPath in propertiesPath)
{
var mainParameter = Expression.Parameter(typeof(Process), "e");
var property = Expression.PropertyOrField(mainParameter, typeof(Process), propertyPath);
test.Add(property);
property = null;
mainParameter = null;
}

return test;
}

我正在尝试从此类获取公共(public)虚拟属性:

public class Process

{

public int? CompanyId { get; set; }

public int? RecommendationId { get; set; }

public int? DiagnosisNodeId { get; set; }

[ForeignKey("DiagnosisId")]
public virtual Diagnosis Diagnosis { get; set; }

[ForeignKey("DiagnosisNodeId")]
public virtual DiagnosisNode DiagnosisNode { get; set; }

[ForeignKey("RecommendationId")]
public virtual Recommendation Recommendation { get; set; }
}

但是在第一次迭代之后,Expression.Property 总是抛出一个异常,即给定的属性在类 Process 中不存在。

有人可以帮我解决这个问题吗?

最佳答案

an example of the propertyPaths is: "Diagnosis, DiagnosisNode"

问题是逗号后面的空格。没有名为 "DiagnosisNode" 的属性(带有前导空格)。对从 Split 返回的字符串使用 .Trim(),或者首先不包含空格。

关于foreach 循环中的 C# Expression.PropertyOrField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447416/

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