【发布时间】:2011-02-24 02:22:55
【问题描述】:
这是为了帮助理解我想要实现的目标而创建的场景。
我正在尝试创建一个返回泛型对象的指定属性的方法
例如
public object getValue<TModel>(TModel item, string propertyName) where TModel : class{
PropertyInfo p = typeof(TModel).GetProperty(propertyName);
return p.GetValue(item, null);
}
如果您正在寻找TModel item 上的属性,上面的代码可以正常工作
例如
string customerName = getValue<Customer>(customer, "name");
但是,如果你想知道客户组的名字是什么,那就成了一个问题: 例如
string customerGroupName = getValue<Customer>(customer, "Group.name");
希望有人能给我一些关于这种出路方案的见解 - 谢谢。
【问题讨论】:
标签: c# generics reflection properties types