这篇文章主要介绍了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> 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类内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
沃梦达教程
本文标题为:C# PropertyInfo类案例详解
猜你喜欢
- Unity3D实现渐变颜色效果 2023-01-16
- .NET CORE DI 依赖注入 2023-09-27
- c# 模拟线性回归的示例 2023-03-14
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity Shader实现模糊效果 2023-04-27
- Oracle中for循环的使用方法 2023-07-04
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- user32.dll 函数说明小结 2022-12-26
- 如何使用C# 捕获进程输出 2023-03-10