gpt4 book ai didi

c# - 获取所有标有 [JsonIgnore] 属性的属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:49 25 4
gpt4 key购买 nike

我有一个带有属性列表的 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>();

关于c# - 获取所有标有 [JsonIgnore] 属性的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39201271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com