您现在的位置是: 首页 > .NET开发 > 文章详情 文章详情
C#利用反射来判断对象是否包含某个属性的实现方法
2019-08-19 【.NET开发】 1392人浏览
public static class SerializeLibrary
{ ///
/// 利用反射来判断对象是否包含某个属性 ///
/// object
/// 需要判断的属性
/// 是否包含
public static bool ContainProperty(this object instance, string propertyName)
{ if (instance != null && !string.IsNullOrEmpty(propertyName))
{
PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName); return (_findedPropertyInfo != null);
} return false;
} ///
/// 获取对象属性值 ///
///
///
///
///
public static string GetObjectPropertyValue(T t, string propertyname)
{
Type type = typeof(T);
PropertyInfo property = type.GetProperty(propertyname); if (property == null)
{ return string.Empty;
} object o = property.GetValue(t, null); if (o == null)
{ return string.Empty;
} return o.ToString();
} ///
/// 获取属性列表 ///
///
public static void GetObjectProperty()
{
Type t = typeof(T);
System.Reflection.PropertyInfo[] properties = t.GetProperties(); foreach (System.Reflection.PropertyInfo info in properties)
{
Console.Write("name=" + info.Name + ";" + "type=" + info.PropertyType.Name + ";value=" + GetObjectPropertyValue
代码使用方法如下:
bool cc = _person.ContainProperty("cc");bool aa = _person.ContainProperty("Age");
很赞哦! (0)
上一篇: C#获取当前主机硬件信息