亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

c# 獲取所有屬性值

c# 獲取所有屬性值

C#
慕娘9325324 2023-09-16 15:52:41
我有一個 IncidentImageModel 類并記錄任何受傷部位。1 或零。我可以使用 Bool 來表示 true 或 false,但不知何故它就是這樣。我想循環遍歷每個屬性,如果屬性值為 1,我想將屬性名稱添加到字符串中。例如,頭 = 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 }
查看完整描述

2 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

如果您只需要值為 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;


查看完整回答
反對 回復 2023-09-16
?
森欄

TA貢獻1810條經驗 獲得超5個贊

這是您的固定代碼:


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}");

}


查看完整回答
反對 回復 2023-09-16
?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

查看完整回答
反對 回復 2023-09-16
  • 2 回答
  • 0 關注
  • 170 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號