gpt4 book ai didi

c# - 获取属性描述属性

转载 作者:太空狗 更新时间:2023-10-30 00:31:25 25 4
gpt4 key购买 nike

现有代码(简化)

我有这个功能

public static string[] GetFieldNames<T>(IEnumerable<T> items)
where T : class
{
var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types

return properties.Select(p => p.Name).ToArray();
}

所以如果说我有这门课

class MyClass {
public string Name { get; set; }

[Description("The value")]
public int Value { get; set; }
}

我可以有这样的代码

List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]

这很好。

问题

我需要获取描述(如果存在),以便 GetFieldNames(items) 返回 ["Name", "The value"]

如何修改 GetFieldNames() 函数以读取 Description 属性(如果存在)?
(请注意,此功能已被简化,实际功能要复杂得多,因此请避免更改逻辑)

最佳答案

这应该适合你:

return properties.Select(p => 
Attribute.IsDefined(p, typeof(DescriptionAttribute)) ?
(Attribute.GetCustomAttribute(p, typeof(DescriptionAttribute)) as DescriptionAttribute).Description:
p.Name
).ToArray();

关于c# - 获取属性描述属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352948/

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