发布时间:2025-12-11 01:01:54 浏览次数:1
对一个对象进行属性分析,并得到相应的属性值,并判断属性的默认值以及空值
publicclassPeople{publicstringname{get;set;}publicintage{get;set;}publicDateTimebirthday{get;set;}publicboolisActive{get;set;}publicList<Address>address{get;set;}}publicclassAddress{publicstringcountry{get;set;}publicstringprovince{get;set;}publicstringcity{get;set;}}classProgram{staticvoidMain(string[]args){List<Address>address=newList<Address>(){newAddress(){country="china",province="anHui",city="bengBu",},newAddress(){country="china",city="shangHai",},};Peoplepeople=newPeople(){name="wangqilong",age=23,birthday=Convert.ToDateTime("2018-09-15"),isActive=true,address=address};stringstr=method(people);}publicstaticstringmethod(Objectobj){stringstr="";TypepostType=obj.GetType();PropertyInfo[]postTypeInfos=postType.GetProperties();//返回为当前Type的所有公共属性,PropertyInfo[]PropertyInfo的所有公共属性的Type对象数组foreach(PropertyInfopinpostTypeInfos){if(p.PropertyType.FullName==typeof(DateTime).FullName){DateTimepValue=(DateTime)p.GetValue(obj,null);if(pValue!=null&&pValue!=DateTime.MinValue)//dateTime类型申明时默认值为最小值{str+=p.Name+":"+pValue+";";}}elseif(p.PropertyType.FullName==typeof(Int32).FullName){intpValue=(int)p.GetValue(obj,null);if(pValue!=0)//int类型申明时默认值为最小值0{str+=p.Name+":"+pValue+";";}}elseif(p.PropertyType.FullName==typeof(Boolean).FullName){ObjectpValue=p.GetValue(obj,null);str+=p.Name+":"+pValue+";";}elseif(p.PropertyType.FullName==typeof(String).FullName){ObjectpValue=p.GetValue(obj,null);str+=p.Name+":"+pValue+";";}//如果传入的对象包含集合,集合中是另个对象elseif(p.PropertyType.FullName==typeof(List<Address>).FullName){List<Address>list=(List<Address>)p.GetValue(obj,null);if(list!=null){foreach(Addressaddressinlist){str+=p.Name+":"+address.country+","+address.province+","+address.city+";";}}}}returnstr;}}结果:”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类的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持本站,关注本站行业资讯频道,更多相关知识等着你来学习!