【问题标题】:How to get the DisplayNameAttribute when it is in another class如何在另一个类中获取 DisplayName 属性
【发布时间】:2014-03-20 18:25:43
【问题描述】:

以下代码有问题:

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

【问题讨论】:

  • 你能解释一下你在另一堂课是什么意思吗?
  • 属性应用于类型,而不是该类型的实例。因此,您的实体的每个实例都将具有完全相同的元数据。我认为您要解决的任何问题的解决方案都是不正确的。您要解决的实际问题是什么?
  • Steve,我正在从 Entity Framework 获取数据并将其写入 Excell 文件。因此,我需要实体的属性并将其写为列标题。但是,我想将属性 cod_person 设置为 Cod。人。我清楚了吗?谢谢你的提问!

标签: c# system.componentmodel


【解决方案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 属性当前不会更改显示名称,因此您不会看到任何差异。更改传递给属性构造函数的值以查看类型描述符是否正常工作。

【讨论】:

  • 谢谢理查德,我正在尝试!
  • 理查德成功了!非常简单的解决方案,你说得很好。非常非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
相关资源
最近更新 更多