1. 程式人生 > >.NET 判斷對象所有屬性是否為空

.NET 判斷對象所有屬性是否為空

ole end exchange 代碼 參考 tac ssi assign pro

如題,此實例考慮對象屬性較多的情況(暫不考慮此對象設計是否合理),當想要驗證眾多對象是否為空時,If Else不在考慮之列,期望用最簡單的代碼實現,如下:

參考:https://codereview.stackexchange.com/questions/70341/check-if-any-of-class-properties-is-not-null-empty-was-assigned

代碼:

ObjectProperties op = new ObjectProperties();
            op.name = "test";
            op.age = 15
; StringBuilder sb = new StringBuilder(); PropertyInfo[] properties = op.GetType().GetProperties(); foreach (PropertyInfo pi in properties) { if (pi.GetValue(op,null) != "" && pi.GetValue(op, null) != null) { sb.Append(
string.Format("Name: {0} | Value: {1}", pi.Name, pi.GetValue(op, null) ) ); } } Console.WriteLine(sb.ToString()); Console.ReadLine(); }

代碼邏輯簡單,控制臺應用程序實現,關鍵代碼 pi.GetValue(op, null) ,已運行通過,達到期望,如有錯,請指正。

.NET 判斷對象所有屬性是否為空