加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#使用Reflection来获取通用对象(及其嵌套对象)属性

发布时间:2020-12-15 04:27:45 所属栏目:百科 来源:网络整理
导读:这是为了帮助了解我想要实现的目的而创建的一个场景. 我正在尝试创建一个返回一个通用对象的指定属性的方法 例如 public object getValueTModel(TModel item,string propertyName) where TModel : class{ PropertyInfo p = typeof(TModel).GetProperty(prope
这是为了帮助了解我想要实现的目的而创建的一个场景.

我正在尝试创建一个返回一个通用对象的指定属性的方法

例如

public object getValue<TModel>(TModel item,string propertyName) where TModel : class{
    PropertyInfo p = typeof(TModel).GetProperty(propertyName);
    return p.GetValue(item,null);
}

如果您正在寻找TModel项目上的一个属性,上面的代码工作正常
例如

string customerName = getValue<Customer>(customer,"name");

但是,如果您想了解客户群组的名称,就成为一个问题:
例如

string customerGroupName = getValue<Customer>(customer,"Group.name");

希望有人能给我一些关于这种方式的洞察力 – 谢谢.

解决方法

在System.Web.UI命名空间中有一个方法:
DataBinder.Eval(source,expression);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读