6

我有一个[Display(Name ="name")]在属性中设置的类,并且[Table("tableName"]在类的顶部。

现在我正在使用反射来获取此类的一些信息,我想知道是否可以以某种方式将 a 添加[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; }
}
4

4 回答 4

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

使用示例

[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
}
于 2013-07-24T05:51:40.730 回答
5

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

于 2013-07-24T06:29:41.547 回答
2

简单地写一个这样的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);
于 2014-03-14T20:09:11.650 回答
0

基于@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)
}

这么多选择:)

于 2014-07-15T17:44:17.523 回答