C# PropertyInfo类案例详解
程序员文章站
2022-03-12 23:18:48
对一个对象进行属性分析,并得到相应的属性值,并判断属性的默认值以及空值 public class people { public string name { get; set; }...
对一个对象进行属性分析,并得到相应的属性值,并判断属性的默认值以及空值
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> 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> address = new list<address>() { 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 = (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 = (int)p.getvalue(obj, null); if (pvalue != 0) //int类型申明时默认值为最小值0 { str += p.name + ":" + pvalue + ";"; } } else if (p.propertytype.fullname == typeof(boolean).fullname) { object pvalue = p.getvalue(obj, null); str += p.name + ":" + pvalue + ";"; } else if (p.propertytype.fullname == typeof(string).fullname) { object pvalue = p.getvalue(obj, null); str += p.name + ":" + pvalue + ";"; } //如果传入的对象包含集合,集合中是另个对象 else if (p.propertytype.fullname == typeof(list<address>).fullname) { list<address> list = (list<address>)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# propertyinfo类案例详解的文章就介绍到这了,更多相关c# propertyinfo类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!