获取类的DisplayName属性值

本文关键字:属性 DisplayName 获取 | 更新日期: 2023-09-27 18:16:23

我花了一个小时试图获得应用于ClassDisplayName属性的值。

我发现从方法和属性中获得属性值足够简单,但我正在与类作斗争。

谁能帮我解决这个相对较小的问题?样本如下:

 [DisplayName("Opportunity")]
 public class Opportunity
 {
  // Code Omitted
 }

的变量
var classDisplayName = typeof(T).GetCustomAttributes(typeof(DisplayNameAttribute),true).FirstOrDefault().ToString();

我花了很多时间在MSDN和SO上,但我想我错过了一些愚蠢的简单的东西。

不管怎样,这也是给未来读者的好问题

任何帮助都非常感谢!

获取类的DisplayName属性值

使用你的例子,我得到它工作这样做:

 var displayName = typeof(Opportunity)
    .GetCustomAttributes(typeof(DisplayNameAttribute), true)
    .FirstOrDefault() as DisplayNameAttribute;
if (displayName != null)
    Console.WriteLine(displayName.DisplayName);

这个输出"Opportunity"。

或者用更一般的方式:

public static string GetDisplayName<T>()
{
    var displayName = typeof(T)
      .GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .FirstOrDefault() as DisplayNameAttribute;
    if (displayName != null)
        return displayName.DisplayName;
     return "";
}

用法:

string displayName = GetDisplayName<Opportunity>();

GetCustomAttributes()返回一个object[],因此您需要在访问所需的属性值之前先应用特定的强制转换。

您需要访问DisplayName属性而不是ToString。你可以通过转换为DisplayNameAttribute来实现。

var classDisplayName =
    ((DisplayNameAttribute)
    typeof(Opportunity)
       .GetCustomAttributes(typeof(DisplayNameAttribute), true)
       .FirstOrDefault()).DisplayName;

已经存在一些有效的解决方案,但是您也可以创建一个这样的扩展方法:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class PropertyExtension
{
    public static string GetDisplayName<T>(this string property)
    {
        MemberInfo propertyInfo = typeof(T).GetProperty(property);
        var displayAttribute = propertyInfo?.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
        return displayAttribute != null ? displayAttribute.Name : "";
    }
}

使用它的方式是提供属性的名称作为字符串,然后是类的类型。

var propertyNameInClass = "DateCreated"; // Could be any property
// You could probably do something like nameof(myOpportunity.DateCreated)
// to keep it strongly-typed
var displayName = propertyNameInClass.GetDisplayName<Opportunity>();
if(!string.IsNullOrEmpty(displayName))
{
    // Do something
}

我认为这比其他一些解决方案更动态,更干净。因为它是动态的,所以用try/catch语句包装它可能是一个好主意。

试试这个:

var classDisplayName = ((DisplayNameAttribute)typeof(Opportunity).GetCustomAttributes(typeof(DisplayNameAttribute), true).FirstOrDefault()).DisplayName;
Console.WriteLine(classDisplayName);

如果使用

[DisplayName("bla")]

using System.ComponentModel;

然后得到"bla"这样的

string name = ((object)myObject).GetType().GetCustomAttribute<DisplayNameAttribute>()?.DisplayName;

或者你可以用

[Display(Name = "bla")]

using System.ComponentModel.DataAnnotations;

,然后得到"bla"这样的

string name = ((object)myObject).GetType().GetCustomAttribute<DisplayAttribute>()?.GetName();

不需要强制转换为object,除非你使用的是动态类型的对象。

因此要回答这个问题,我想下一段代码会用到

这个技巧
string name = typeof(T).GetCustomAttribute<DisplayNameAttribute>()?.DisplayName;