您的位置:首页 > 其它

类的属性取值与赋值

2013-05-10 11:24 127 查看
/// <summary>
/// 从类的属性中获取属性值
/// </summary>
/// <param name="p_Instance">属性的容器</param>
/// <param name="p_PropertyName">属性名</param>
/// <param name="blThrowException">是否抛出异常</param>
/// <returns></returns>
public static object GetPropertyValue(object p_Instance, string p_PropertyName, bool blThrowException)
{
Type MyType = p_Instance.GetType();
PropertyInfo pi = MyType.GetProperty(p_PropertyName);
if (blThrowException)
{
if (pi == null)
{
throw new Exception("在类:[" + MyType.FullName + "] 中不存在属性名为:[" + p_PropertyName + "] 的属性");
}

return pi.GetValue(p_Instance, null);
}

if (pi == null)
{
return null;
}

return pi.GetValue(p_Instance, null);
}
/// <summary>
/// 设置类的属性值
/// </summary>
/// <param name="p_Instance"></param>
/// <param name="p_PropertyName"></param>
/// <param name="p_Value"></param>
public static void SetPropertyValue(object p_Instance, string p_PropertyName, object p_Value)
{
Type MyType = p_Instance.GetType();
PropertyInfo pi = MyType.GetProperty(p_PropertyName);
if (pi == null)
{
throw new Exception("在类:[" + MyType.FullName + "] 中不存在属性名为:[" + p_PropertyName + "] 的属性");
}
if (pi.CanWrite)
{
switch (pi.PropertyType.FullName)
{
case "System.Int32":
pi.SetValue(p_Instance, StringToInt(ObjectToNullStr(p_Value)), null);
break;

case "System.DateTime":
pi.SetValue(p_Instance, StringToDate(ObjectToNullStr(p_Value)), null);
break;
default:
pi.SetValue(p_Instance, p_Value, null);
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐