如何获得DisplayNameAttribute时,它是在另一个类

本文关键字:另一个 何获得 DisplayNameAttribute | 更新日期: 2023-09-27 17:51:11

我有一个问题与以下代码:

//This class can't be changed for is part of an EF data context.
public partial class person
{
    public string Name { get; set; }
}
//I have this partial just to access the person DisplayNameAttribute 
[MetadataType(typeof(person_metaData))]
public partial class person
{
}
//And this is the MetaData where i am placing the 
public class person_metaData
{
    [DisplayName("Name")]
    public string Name { get; set; }
}

我如何得到DisplayNameAttribute时,它是在另一个类?先谢谢你!

如何获得DisplayNameAttribute时,它是在另一个类

假设您的类的AssociatedMetadataTypeTypeDescriptionProvider已正确注册,则System.ComponentModel.TypeDescriptor类将尊重元数据类的属性。

在程序开头的某个地方添加:

TypeDescriptor.AddProvider(
    new AssociatedMetadataTypeTypeDescriptionProvider(typeof(person)), 
    typeof(person));

然后访问属性:

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(person));
PropertyDescriptor prop = properties["Name"];
string displayName = prop.DisplayName;

或者,您可以直接使用AssociatedMetadataTypeTypeDescriptionProvider类:

var provider = new AssociatedMetadataTypeTypeDescriptionProvider(typeof(person));
ICustomTypeDescriptor typeDescriptor = provider.GetTypeDescriptor(typeof(person), null);
PropertyDescriptorCollection properties = typeDescriptor.GetProperties();
PropertyDescriptor prop = properties["Name"];
string displayName = prop.DisplayName;

NB:您的DisplayName属性当前不会更改显示名称,因此您不会看到任何差异。更改传递给属性构造函数的值,以查看类型描述符是否正常工作。