使用c#的类的"显示名称"数据注释

est*_*e97 6 c# reflection data-annotations

[Display(Name ="name")]在属性中有一个带有set 的类,并且[Table("tableName"]在类的顶部.

现在我正在使用反射来获取这个类的一些信息,我想知道我是否能以某种方式[Display(Name ="name")]向类本身添加一个.

它会是这样的

[Table("MyObjectTable")]
[Display(Name ="My Class Name")]     <-------------- New Annotation
public class MyObject
{
   [Required]
   public int Id { get; set; }

   [Display(Name="My Property Name")]
   public string PropertyName{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ray 8

根据那篇文章,我引用了一个完整的例子

声明自定义属性

[System.AttributeUsage(System.AttributeTargets.Class)]
public class Display : System.Attribute
{
    private string _name;

    public Display(string name)
    {
        _name = name;        
    }

    public string GetName()
    {
        return _name;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用示例

[Display("My Class Name")]
public class MyClass
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

读取属性的示例

public static string GetDisplayAttributeValue()
{
    System.Attribute[] attrs = 
            System.Attribute.GetCustomAttributes(typeof(MyClass)); 

    foreach (System.Attribute attr in attrs)
    {
        var displayAttribute as Display;
        if (displayAttribute == null)
            continue;
        return displayAttribute.GetName();   
    }

    // throw not found exception or just return string.Empty
}
Run Code Online (Sandbox Code Playgroud)


Nik*_*a B 5

.Net 中已经有一个属性:http : //msdn.microsoft.com/en-us/library/system.componentmodel.displaynameattribute.aspx。是的,您可以在以下两者上使用它:属性和类(检查AttributeUsageAttribute语法部分)