“显示名称”使用C#的类的数据注释 [英] "Display Name" Data Annotation for class using c#

查看:132
本文介绍了“显示名称”使用C#的类的数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,其中在属性中设置了 [Display(Name = name)] ,并且 [Table( tableName]

I have a class with [Display(Name ="name")] set in the properties, and [Table("tableName"] in the top of the class.

现在,我正在使用反射来获取有关该类的一些信息,我想知道是否以某种方式可以为类本身添加 [Display(Name = name)]

Now I'm using reflection to get some information of this class and I'm wondering if somehow I can add a [Display(Name ="name")] to the class itself.

[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; }
}


推荐答案

基于该文章,我引用了以下完整示例

Based on that article I referenced heres a complete example

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

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

    public string GetName()
    {
        return _name;
    }
}



使用示例



Example of use

[Display("My Class Name")]
public class MyClass
{
    // ...
}



读取属性示例



Example of reading attribute

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
}

这篇关于“显示名称”使用C#的类的数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆