C#|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{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 = new List(){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 = https://www.it610.com/article/(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 = https://www.it610.com/article/(int)p.GetValue(obj, null); if (pValue != 0)//int类型申明时默认值为最小值0{str += p.Name +":" + pValue + "; "; }}else if (p.PropertyType.FullName == typeof(Boolean).FullName){Object pValue = https://www.it610.com/article/p.GetValue(obj, null); str += p.Name +":" + pValue + "; "; }else if (p.PropertyType.FullName == typeof(String).FullName){Object pValue = https://www.it610.com/article/p.GetValue(obj, null); str += p.Name +":" + pValue + "; "; }//如果传入的对象包含集合,集合中是另个对象else if (p.PropertyType.FullName == typeof(List).FullName){List list = (List)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#|C# PropertyInfo类案例详解】到此这篇关于C# PropertyInfo类案例详解的文章就介绍到这了,更多相关C# PropertyInfo类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 为什么你的路演总会超时()
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- thinkphp|thinkphp 3.2 如何调用第三方类库
- 使用composer自动加载类文件
- 一个健康的APP和健全的人格大体类似
- 种树郭橐驼传(文言句式+古今异义+词类活用+通假字)
- 归乡-序章(世界伊始,人类无所依靠,我的故事就从这里开始...)
- jQuery插件
- 第十六天(请介绍一件让你非常自豪的事情,(不能是职业类的),什么原因感到自豪。)