会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
编写人生
写写代码,写写人生
博客园
首页
新随笔
联系
管理
订阅
补充一个技术文章吧,否则真的对不起博客园
/**/
///
<summary>
较安全的返回指定属性的值
</summary>
///
<remarks>
///
例如,如果你想获得Company的CompanyCode的DefaultCode属性,可以使用
///
<code>
///
object code = _company.SafeGetValue("CompanyCode.DefaultCode");
///
</code>
///
但注意:
///
传入的参数(属性名)不允许书写错误,在此方法中不对此进行检查;
///
</remarks>
public
object
SafeGetValue(
string
propertyName)
{
string
[] props
=
propertyName.Split(
'
.
'
);
string
propName;
PropertyInfo propInfo;
object
obj
=
this
;
Type objType;
for
(
int
i
=
0
; i
<
props.Length; i
++
)
{
objType
=
obj.GetType();
propName
=
props[i];
if
(propName.Trim().Length
==
0
)
throw
new
ArgumentException(
"
propertyName
"
);
try
{
propInfo
=
objType.GetProperty(propName);
if
(propInfo
==
null
)
throw
new
ArgumentException(
"
propertyName
"
);
obj
=
propInfo.GetValue(obj,
null
);
}
catch
(AmbiguousMatchException)
{
PropertyDescriptorCollection propDescs
=
TypeDescriptor.GetProperties(objType);
PropertyDescriptor propDesc
=
propDescs.Find(propName,
false
);
if
(propDesc
==
null
)
throw
new
ArgumentException(
"
propertyName
"
);
else
{
obj
=
propDesc.GetValue(obj);
}
}
if
(obj
==
null
)
return
null
;
}
return
obj;
}
posted on
2004-12-29 12:11
编写人生
阅读(
507
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部