【问题标题】:.NET : Get property name in attribute.NET:在属性中获取属性名称
【发布时间】:2010-05-09 11:04:18
【问题描述】:
[MyAttribute()]
public string Name { get; set; }

MyAttribute我需要知道关联属性的名称,可以吗?

编辑:

我需要在文本格式中使用它。

【问题讨论】:

  • 你能详细说明你为什么需要它以及你会用它做什么吗?

标签: .net attributes


【解决方案1】:

不,这是不可能的。通常您会使用reflection to read attributes 应用于给定属性,因此您已经知道该属性。示例:

var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}

【讨论】:

  • 嗯,可能是我从另一端看问题而不是我应该的。
  • 是的,您从一个类型开始,然后获取属性,最后读取应用于给定属性的自定义属性。
【解决方案2】:

您可以使用PostSharp 方面来完成这项工作。不久前我有一个类似的question,这几乎是一回事。您可以在答案中查看 cmets 以获取有关您可能遇到的一些影响的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2021-12-04
    • 1970-01-01
    • 2014-10-27
    • 2010-11-05
    • 2012-01-08
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多