获取类 DisplayName 属性值 [英] Get class DisplayName attribute value

查看:27
本文介绍了获取类 DisplayName 属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了最后一个小时试图获取应用于 ClassDisplayName 属性的值.

Iv'e spent the last hour trying to get the value of a DisplayName attribute that's applied to a Class.

我发现从方法和属性中获取属性值很简单,但我在类中苦苦挣扎.

I find it simple enough to get the attribute values from methods and properties but I'm struggling with the class.

有人能帮我解决这个相对较小的问题吗?

Could anyone help me out with this relatively small issue?

示例如下:

班级

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

变量

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

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

I have spent much time on MSDN and SO but I guess I'm missing something stupidly simple.

对于未来的读者来说,这也是一个很好的问题

Either way great question for future readers too

非常感谢任何帮助!

推荐答案

使用您的示例,我可以这样做:

using your example I got it working doing this:

 var displayName = typeof(Opportunity)
    .GetCustomAttributes(typeof(DisplayNameAttribute), true)
    .FirstOrDefault() as DisplayNameAttribute;

if (displayName != null)
    Console.WriteLine(displayName.DisplayName);

这输出了机会".

或者对于您似乎正在做的更通用的方式:

Or for the more generic way you seem to be doing it:

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[],因此您需要先应用特定的转换,然后才能访问所需的属性值.

GetCustomAttributes() returns an object[], so you need to apply the specific cast first before accessing the required property values.

这篇关于获取类 DisplayName 属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆