获取所有标有 [JsonIgnore] 属性的属性

elv*_*iuz 2 .net c# reflection

我有一个 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; }
}
Run Code Online (Sandbox Code Playgroud)

我想检索未用 [JsonIgnore] 属性标记的属性。

JsonIgnore 是http://www.newtonsoft.com/json的一个属性

所以,在这个例子中,我想拥有属性“Prop2”。

我尝试过

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(JsonIgnore)));
Run Code Online (Sandbox Code Playgroud)

或者

var props = t.GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(Newtonsoft.Json.JsonIgnoreAttribute)));
Run Code Online (Sandbox Code Playgroud)

其中t是 MyClass 的类型,但该方法返回 0 个元素。

你能帮我吗?谢谢

Ste*_*nio 8

typeof(MyClass).GetProperties()
               .Where(property => 
                      property.GetCustomAttributes(false)
                              .OfType<JsonIgnoreAttribute>()
                              .Any()
                     );
Run Code Online (Sandbox Code Playgroud)

在调用中指定类型GetCustomAttibutes可以提高性能,此外,您可能希望逻辑可重用,因此可以使用此辅助方法:

static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TType, TAttribute>()
{
    Func<PropertyInfo, bool> matching = 
            property => property.GetCustomAttributes(typeof(TAttribute), false)
                                .Any();

    return typeof(TType).GetProperties().Where(matching);
}
Run Code Online (Sandbox Code Playgroud)

用法:

var properties = GetPropertyWithAttribute<MyClass, JsonIgnoreAttribute>();
Run Code Online (Sandbox Code Playgroud)

编辑: 我不确定,但您可能在没有属性的属性之后,所以您可以否定查找谓词:

static IEnumerable<PropertyInfo> GetPropertiesWithoutAttribute<TType, TAttribute>()
{
    Func<PropertyInfo, bool> matching =
            property => !property.GetCustomAttributes(typeof(TAttribute), false)
                                .Any();

    return typeof(TType).GetProperties().Where(matching);
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用简单的库,例如Fasterflect

typeof(MyClass).PropertiesWith<JsonIgnoreAttribute>();
Run Code Online (Sandbox Code Playgroud)