1

我对以下代码有疑问:

//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?提前致谢!

4

1 回答 1

1

假设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;

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

于 2014-03-20T19:45:20.780 回答