【发布时间】:2014-02-12 18:55:41
【问题描述】:
我需要一个 linq 查询,它根据名称值为“Foo”FIRST 的 XmlElementAttribute 查找对象的属性名称,如果不是,则只需给出属性名称。因此,查询将返回属性名称的单个字符串或 null 这些条件都不存在。
例子:
public class MyClass
{
[XmlElement("Foo")]
public int MyInt {get; set;}
[XmlElement("FooString")]
public string MyString {get; set;}
}
因此,如果我想查找“MyInt”但给定的是“Foo”,则查询将首先查看它是否找到名称为“Foo”的 XmlElementAttribute 的属性。如果没有,那么只需匹配属性名称即可找到“MyInt”。如果找不到“MyInt”,则该值为 null。
这是我目前所拥有的(不正确):
var propertyName = targetObject.GetType().GetProperties()
.Select(property => new {property, attributes = property.GetCustomAttributes(true)})
.Where(@t => @t.attributes.Any())
.SelectMany(@t => @t.attributes, (@t, attribute) => new {@t, attribute})
.Where(@t => @t.attribute.GetType() == typeof(XmlElementAttribute))
.Select(@t => @t);
显然更干净的实现是受欢迎的。
【问题讨论】:
标签: c# linq reflection properties attributes