如何获取枚举的自定义属性值

如何获取枚举的自定义属性值

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

问题描述

我有一个枚举,其中每个成员都应用了一个自定义属性.如何检索存储在每个属性中的值?

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 可以转换为任何枚举,对吗?这就是我退货的原因.

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.

忘了说,上面的代码对于每个枚举成员都返回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.

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

08-06 06:29