如题,此实例考虑对象属性较多的情况(暂不考虑此对象设计是否合理),当想要验证众多对象是否为空时,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) ,已运行通过,达到期望,如有错,请指正。

相关文章:

  • 2021-10-16
  • 2022-02-05
  • 2021-12-07
  • 2022-01-21
  • 2021-12-07
猜你喜欢
  • 2021-11-27
  • 2022-12-23
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案