代码之家  ›  专栏  ›  技术社区  ›  Feryt

.NET:在属性中获取属性名

  •  6
  • Feryt  · 技术社区  · 15 年前
    [MyAttribute()]
    public string Name { get; set; }
    

    MyAttribute 我需要知道相关财产的名称,有可能吗?

    编辑:

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

    2 回复  |  直到 15 年前
        1
  •  8
  •   Darin Dimitrov    15 年前

    不,这是不可能的。通常你会用 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
  •  0
  •   Community CDub    8 年前

    你可以用 PostSharp 工作方面。我有一个类似的 question 前一阵子,这几乎是同一件事。您可以查看答案上的注释,以获取有关您可能遇到的某些含义的更多信息。