反射获得对象的值

反射获得对象指定name的值

用途:用于绑定数据对象支持广泛的类型

1、DataRow中列name

2、键值集合中的name

3、字典数据中name

4、类的name字段(类支持子类)

/// <summary>
/// 获取对象中指定name的值
/// </summary>
/// <param name="obj">DataRowView和实体类对象</param>
/// <param name="name">字段或类成员</param>
/// <returns></returns>
public static object GetValue(object obj, string name)
{
if (obj == null || String.IsNullOrEmpty(name))
{
return null;
}
//DataRow优先
if (obj is DataRowView || obj is DataRow)
{
return DataHelper.GetValue(obj, name);
}
//键值集合
if (obj is NameValueCollection)
{
return ((NameValueCollection)obj)[name];
}
//实现了IDictionary接口的类
if (obj.GetType().GetInterface("IDictionary", true) != null)
{
return ((IDictionary)obj)[name];
}
//类反射
int p = name.IndexOf(".");
if (p == -1)
{
int ps = name.IndexOf("(");
if (ps == -1)
{
//属性
PropertyInfo pInfo = obj.GetType().GetProperty(name);
if (pInfo != null)
{
return pInfo.GetValue(obj, null);
}
//字段
FieldInfo fInfo = obj.GetType().GetField(name);
if (fInfo != null)
{
return fInfo.GetValue(obj);
}
//方法
MethodInfo mInfo = obj.GetType().GetMethod(name);
if (mInfo != null)
{
return mInfo.Invoke(obj, null);
}
else
{
return null;
}
}
else
{
//带参数方法
int pe = name.IndexOf(")");
if (pe == -1)
{
pe = name.Length;
}
MethodInfo mInfo = obj.GetType().GetMethod(name.Substring(0, ps));
if (mInfo != null)
{
return mInfo.Invoke(obj, DataHelper.GetStrings(name.Substring(ps + 1, pe - ps - 1).Replace("'", "")));
}
else
{
return null;
}
}
}
else
{
//包含子类
string name1 = name.Substring(0, p);
object obj1 = null;
PropertyInfo pInfo = obj.GetType().GetProperty(name1);
if (pInfo != null)
{
obj1 = pInfo.GetValue(obj, null);
}
else
{
FieldInfo fInfo = obj.GetType().GetField(name1);
if (fInfo != null)
{
obj1 = fInfo.GetValue(obj);
}
}
if (obj1 == null)
{
return null;
}
else
{
return GetValue(obj1, name.Substring(p + 1));
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值