简体   繁体   English

获取作为lambda表达式传递的参数的PropertyInfo | 紧凑框架,C#

[英]Get PropertyInfo of a parameter passed as lambda expression | Compact Framework, C#

Say I have following Asset class: 说我有以下资产类别:

class Asset
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now I want to write a method GetPropertyInfo(a=>a.Name); 现在,我想编写一个方法GetPropertyInfo(a=>a.Name); and this method gives me the PropertyInfo of Asset.Name. 这个方法给了我Asset.Name的PropertyInfo。 I should be able to call this method like: 我应该可以像这样调用此方法:

EDIT Example Method Call 编辑示例方法调用

PropertyInfo propInfo = GetPropertyInfo(a=>a.Name);

I have a List<PropertyInfo> so I want to match a given lambda expression with those in my list. 我有一个List<PropertyInfo>所以我想将给定的lambda表达式与列表中的表达式匹配。

if(Possible on Compact Framework 3.5 && using C#)
    How?
else
    Please Notify

Thanks. 谢谢。

This can be done under .NETCF 3.5. 这可以在.NETCF 3.5下完成。

private List<Asset> m_list;

private Asset[] GetPropertyInfo(string name) {
  var items = m_list.Where(a => a.Name == name);
  if (items != null) {
    return items.ToArray();
  } else {
    return null;
  }
}

You will, however, need to initialize the m_list and fill it with your data first. 但是,您将需要初始化m_list并首先将其填充数据。

UPDATE: 更新:

So, your list is of type PropertyInfo and you want a call to get the type that matches a particular Asset object. 因此,您的列表的类型为PropertyInfo并且您希望调用以获取与特定Asset对象匹配的类型。

If that is correct, you could simply edit the code above to be as follows: 如果正确,则可以简单地将上面的代码编辑如下:

private List<PropertyInfo> m_list;

private PropertyInfo GetPropertyInfo(Asset a) {
  return m_list.FirstOrDefault(x => x.Name == a.Name);
}

I am not sure how you are getting the List<PropertyInfo> , though. 我不确定您如何获取List<PropertyInfo> I was able to pull a single PropertyInfo object using the code below: 我可以使用以下代码提取单个PropertyInfo对象:

private PropertyInfo GetPropertyInfo() {
  var t = Type.GetType("System.Reflection.MemberInfo");
  return t.GetProperty("Name");
}

There was nothing useful in this item. 这个项目没有什么用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM