System.ComponentModel.DescriptionAttribute in portable class library

后端 未结 3 1247
灰色年华
灰色年华 2020-12-29 23:03

I am using the Description attribute in my enums to provide a user friendly name to an enum field. e.g.

public enum InstallationType
{
    [Description(\"For         


        
3条回答
  •  臣服心动
    2020-12-29 23:07

    Whether something is available to a portable class library depends a bit on exactly which frameworks you selected for the library - you get the strict intersection only. However, it could well be that this attribute simply doesn't exist in one of your targeted frameworks. In which case, one option is add your own - then you know it is available. For example:

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public class EnumDescriptionAttribute :Attribute
    {
        private readonly string description;
        public string Description { get { return description; } }
        public EnumDescriptionAttribute(string description)
        {
            this.description = description;
        }
    }
    
    enum Foo
    {
        [EnumDescription("abc")]
        A,
        [EnumDescription("def")]
        B
    }
    

    Note that I intentionally haven't included the additional serialization construtors here, because those too depend on features that are not available on all frameworks. Changing your code from using [Description] / DescriptionAttribute to [EnumDescription] / EnumDescriptionAttribute should be fairly trivial.

提交回复
热议问题