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


如題,此實例考慮對象屬性較多的情況(暫不考慮此對象設計是否合理),當想要驗證眾多對象是否為空時,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) ,已運行通過,達到期望,如有錯,請指正。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM