繁体   English   中英

C#获取所有属性值

[英]c# Get all properties value

我有一个IncidentImageModel类,并保留了任何受伤部位的记录。 1或零。 我可以将Bool用作是非题,但不知何故。

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

例如,Head = 1,左手= 1,右脚=1。但是身体其余部位的值为0。

我如何获得身体部位的清单是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;
}

我知道我可以为每个身体部位做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;

这是您的固定代码:

PropertyInfo[] properties = incident.GetType().GetProperties();
for (int i = 0; i < properties.Length; i++)
{
    var pName = properties[i].Name;
    var pValue = properties[i].GetValue(incident);
    Console.WriteLine($"{pName} = {pValue}");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM