我有一个带有属性列表的 MyClass 类。
public class MyClass
{
[Attribute1]
[Attribute2]
[JsonIgnore]
public int? Prop1 { get; set; }
[Attribute1]
[Attribute8]
public int? Prop2 { get; set; }
[JsonIgnore]
[Attribute2]
public int Prop3 { get; set; }
}
我想检索没有用 [JsonIgnore] 属性标记的属性。
JsonIgnore 是 http://www.newtonsoft.com/json 的一个属性
所以,在这个例子中,我想要属性“Prop2”。
我试过
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(JsonIgnore)));
或
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(Newtonsoft.Json.JsonIgnoreAttribute)));
其中 t 是 MyClass 的类型,但该方法返回 0 个元素。
你能帮帮我吗? 谢谢
请您参考如下方法:
typeof(MyClass).GetProperties()
.Where(property =>
property.GetCustomAttributes(false)
.OfType<JsonIgnoreAttribute>()
.Any()
);
在 GetCustomAttibutes 调用中指定类型可以提高性能,此外,您可能希望逻辑可重用,因此您可以使用此辅助方法:
static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TType, TAttribute>()
{
Func<PropertyInfo, bool> matching =
property => property.GetCustomAttributes(typeof(TAttribute), false)
.Any();
return typeof(TType).GetProperties().Where(matching);
}
用法:
var properties = GetPropertyWithAttribute<MyClass, JsonIgnoreAttribute>();
编辑: 我不确定,但您可能在没有属性的属性之后,所以您可以否定查找谓词:
static IEnumerable<PropertyInfo> GetPropertiesWithoutAttribute<TType, TAttribute>()
{
Func<PropertyInfo, bool> matching =
property => !property.GetCustomAttributes(typeof(TAttribute), false)
.Any();
return typeof(TType).GetProperties().Where(matching);
}
或者您可以使用简单的库,例如 Fasterflect:
typeof(MyClass).PropertiesWith<JsonIgnoreAttribute>();
