Why is a Nullable not a valid Custom Attribute Parameter when T is?

前端 未结 4 2123
猫巷女王i
猫巷女王i 2020-12-30 22:07

If I have an enum like this

public enum Hungry
{
    Somewhat,
    Very,
    CouldEatMySocks
}

and a custom attribute like this

<         


        
4条回答
  •  轮回少年
    2020-12-30 23:03

    To get around this create another initializer in your Attribute:

    class Program
    {
      [Hunger()]
      static void Main(string[] args)
      {
      }
    
      public sealed class HungerAttribute : Attribute
      {        
        public Hungry? HungerLevel { get; }
        public bool IsNull => !_HungerLevel.HasValue;
    
        public HungerAttribute()
        {
        }
    
        //Or:
        public HungerAttribute(Hungry level)
        {
          HungerLevel = level;
        }
      }
    
      public enum Hungry { Somewhat, Very, CouldEatMySocks }
    }
    

    I understand that you're not going to use both properties.

提交回复
热议问题