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

本文关键字:数据 注释 使用 quot 显示 | 更新日期: 2023-09-27 18:24:41

我有一个在属性中设置了[Display(Name ="name")]的类,[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; }
}

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

基于那篇文章,我在这里引用了一个完整的示例

声明自定义属性

[System.AttributeUsage(System.AttributeTargets.Class)]
public class Display : System.Attribute
{
    private string _name;
    public Display(string name)
    {
        _name = name;        
    }
    public string GetName()
    {
        return _name;
    }
}

使用示例

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

读取属性示例

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
}

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

只需编写一个static函数,如下所示:

public static string GetDisplayName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
{
    return ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, new ViewDataDictionary<TModel>(model)).DisplayName;
}

使用这样的:

string name = GetDisplayName(Model, m => m.Prop);

基于@amirhossein mehrvarzi,我使用了这个函数

public static string GetDisplayName(this object model, string expression)
{
    return ModelMetadata.FromStringExpression(expression, new ViewDataDictionary(model)).DisplayName ?? expression;
}

在这个例子中使用了

var test = new MyObject();
foreach (var item in test.GetType().GetProperties())
{
        var temp = test.GetDisplayName(item.Name)
}

这么多选项:)