您好,登錄后才能下訂單哦!
這篇文章主要介紹了C#中PropertyInfo類的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
對一個對象進行屬性分析,并得到相應的屬性值,并判斷屬性的默認值以及空值
public class People { public string name { get; set; } public int age { get; set; } public DateTime birthday { get; set; } public bool isActive { get; set; } public List<Address> address{get;set;} } public class Address { public string country { get; set; } public string province { get; set; } public string city { get; set; } } class Program { static void Main(string[] args) { List<Address> address = new List<Address>() { new Address(){ country="china", province="anHui", city="bengBu", }, new Address(){ country="china", city="shangHai", }, }; People people = new People() { name="wangqilong", age=23, birthday=Convert.ToDateTime("2018-09-15"), isActive=true, address=address }; string str = method(people); } public static string method(Object obj) { string str = ""; Type postType = obj.GetType(); PropertyInfo[] postTypeInfos = postType.GetProperties(); //返回為當前 Type 的所有公共屬性,PropertyInfo[] PropertyInfo 的所有公共屬性的 Type 對象數組 foreach (PropertyInfo p in postTypeInfos) { if (p.PropertyType.FullName == typeof(DateTime).FullName) { DateTime pValue = (DateTime)p.GetValue(obj, null); if (pValue != null && pValue != DateTime.MinValue) //dateTime類型申明時默認值為最小值 { str += p.Name + ":" + pValue + ";"; } } else if (p.PropertyType.FullName == typeof(Int32).FullName) { int pValue = (int)p.GetValue(obj, null); if (pValue != 0) //int類型申明時默認值為最小值0 { str += p.Name + ":" + pValue + ";"; } } else if (p.PropertyType.FullName == typeof(Boolean).FullName) { Object pValue = p.GetValue(obj, null); str += p.Name + ":" + pValue + ";"; } else if (p.PropertyType.FullName == typeof(String).FullName) { Object pValue = p.GetValue(obj, null); str += p.Name + ":" + pValue + ";"; } //如果傳入的對象包含集合,集合中是另個對象 else if (p.PropertyType.FullName == typeof(List<Address>).FullName) { List<Address> list = (List<Address>)p.GetValue(obj, null); if (list != null) { foreach (Address address in list) { str += p.Name + ":" + address.country+","+address.province+","+address.city + ";"; } } } } return str; } }
結果:”name:wangqilong;age:23;birthday:2018/9/15 0:00:00;isActive:True;address:china,anHui,bengBu;address:china,,shangHai;”
關于PropertyInfo類信息: https://docs.microsoft.com/zh-cn/dotnet/api/system.reflection.propertyinfo?view=netframework-1.1
感謝你能夠認真閱讀完這篇文章,希望小編分享的“C#中PropertyInfo類的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。