gpt4 book ai didi

c#获取所有属性值

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:52 26 4
gpt4 key购买 nike

我有一个 IncidentImageModel 类并记录任何受伤部位。 1 或零。我可以使用 Bool 来表示 true 或 false,但不知何故就是这样。

我想遍历每个属性,如果属性值为 1,我想将属性名称添加到字符串。

例如,头 = 1,左手 = 1,右脚 = 1。但其余 body 部位的值为 0。

我怎样才能得到 body 部位的列表是 1?

public class IncidentImageModel
{
[Key]
public int IncidentImageID { get; set; }
public int IncidentID { get; set; }
public int ClientID { get; set; }
public int Head { get; set; } = 0;
public int Neck { get; set; } = 0;

public int RightShoulder { get; set; } = 0;
public int LeftShoulder { get; set; } = 0;
public int Chest { get; set; } = 0;

public int RightArm { get; set; } = 0;
public int LeftArm { get; set; } = 0;
public int LowerAbdomin { get; set; } = 0;

public int RightHand { get; set; } = 0;
public int Genitals { get; set; } = 0;
public int LeftHand { get; set; } = 0;

public int LeftUperLeg { get; set; } = 0;
public int RightUperLeg { get; set; } = 0;

public int RightLowerLeg { get; set; } = 0;
public int LeftLowerLeg { get; set; } = 0;

public int RightFeet { get; set; } = 0;
public int LeftFeet { get; set; } = 0;
}

我知道我可以对每个 body 部位执行 if(),但我确信有更好的方法来做到这一点。如果有人知道该怎么做。

我尝试了这个并获取了所有属性,但无法获取属性值。

 PropertyInfo[] properties = 
incident.IncidentImageModels.GetType().GetProperties();
for(int i=0; i<properties.count();i++)
{
properties[i].Name
}

最佳答案

如果您只需要值为 1 的属性和值,则可以将 GetValue 方法与 LINQ 结合使用:

var incidentImageModel = new IncidentImageModel();
PropertyInfo[] properties = incidentImageModel.GetType().GetProperties();

var result = from property in properties
let nameAndValue = new { property.Name, Value = (int)property.GetValue(incidentImageModel) }
where nameAndValue.Value == 1
select nameAndValue;

关于c#获取所有属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609394/

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