如何获得自定义属性值枚举? [英] How to get Custom Attribute values for enums?

查看:332
本文介绍了如何获得自定义属性值枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,其中每个成员都有一个应用于它的自定义属性。我怎样才能检索存储在每个属性的值?

I have an enum where each member has a custom attribute applied to it. How can I retrieve the value stored in each attribute?

现在我做到这一点:

var attributes = typeof ( EffectType ).GetCustomAttributes ( false );
foreach ( object attribute in attributes )
{
    GPUShaderAttribute attr = ( GPUShaderAttribute ) attribute;
    if ( attr != null )
        return attr.GPUShader;
}
return 0;

另一个问题是,如果没有找到,我应该怎么回报? 0 implcity转换为任何枚举,对不对?这就是为什么我返回。

Another issue is, if it's not found, what should I return? 0 is implcity convertible to any enum, right? That's why I returned that.

忘了说,上面code返回0,每枚举成员。

Forgot to mention, the above code returns 0 for every enum member.

推荐答案

这是一个有点乱做你正在尝试做的,你必须使用反射什么:

It is a bit messy to do what you are trying to do as you have to use reflection:

public GPUShaderAttribute GetGPUShader(EffectType effectType)
{
    MemberInfo memberInfo = typeof(EffectType).GetMember(effectType.ToString())
                                              .FirstOrDefault();

    if (memberInfo != null)
    {
        GPUShaderAttribute attribute = (GPUShaderAttribute) 
                     memberInfo.GetCustomAttributes(typeof(GPUShaderAttribute), false)
                               .FirstOrDefault();
        return attribute;
    }

    return null;
}

这将返回的实例 GPUShaderAttribute ,是有关一个标记上 EffectType 。你必须把它的 EffectType 枚举的特定值:

This will return an instance of the GPUShaderAttribute that is relevant to the one marked up on the enum value of EffectType. You have to call it on a specific value of the EffectType enum:

GPUShaderAttribute attribute = GetGPUShader(EffectType.MyEffect);

一旦有了属性的情况下,你可以得到的具体数值出它是对个人枚举值标记的。

Once you have the instance of the attribute, you can get the specific values out of it that are marked-up on the individual enum values.

这篇关于如何获得自定义属性值枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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