How to get Custom Attribute values for enums?

前端 未结 6 1582
独厮守ぢ
独厮守ぢ 2020-12-05 12:45

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

Right now I do this:

va         


        
6条回答
  •  长情又很酷
    2020-12-05 13:23

    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;
    }
    

    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.

提交回复
热议问题