通过反射获得属性值
2017-10-14 20:23:28 访问(1672) 赞(0) 踩(0)
/// <summary>
/// 获得属性值 - 如果找不到对应的_propertyName,抛出异常
/// </summary>
/// <param name="_propertyName">字段名(如:TheName)/大小写模糊</param>
/// <returns></returns>
public virtual object GetPropertyValue
(
string _propertyName
)
{
Type thisType = this.GetType();
PropertyInfo info = thisType.GetProperty
(
_propertyName,
BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Instance
);
if (info == null)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "PropertyInfo info = thisType.GetProperty(_propertyName[" + _propertyName + "]);"
);
}
return info.GetValue(this, null);
}
/// <summary>
/// 获得属性值 - 如果找不到对应的_propertyName,throwException属性判断是否抛出异常
/// </summary>
/// <param name="_propertyName">字段名(如:TheName)/大小写模糊</param>
/// <param name="throwException">找不到记录是否抛出异常</param>
/// <param name="defaultValue">如果不抛出异常,默认返回值</param>
/// <returns></returns>
public virtual object GetPropertyValue
(
string _propertyName,
bool throwException,
object defaultValue
)
{
Type thisType = this.GetType();
PropertyInfo info = thisType.GetProperty
(
_propertyName,
BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Instance
);
if (info == null)
{
if (throwException)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "PropertyInfo info = thisType.GetProperty(_propertyName[" + _propertyName + "]);"
);
}
return defaultValue;
}
return info.GetValue(this, null);
}
上一条:
下一条:
相关评论
发表评论