If I have an enum like this
public enum Hungry { Somewhat, Very, CouldEatMySocks }and a custom attribute like this
public class HungerAttribute : Attribute { public Hungry HungerLevel { get; set; } public Hungry? NullableHungerLevel { get; set; } }I can do this
[Hunger(HungerLevel = Hungry.CouldEatMySocks)] public class Thing1but I can't do this
[Hunger(NullableHungerLevel = Hungry.CouldEatMySocks)] public class Thing2It generates an error that says "'NullableHungerLevel' is not a valid named attribute argument because it is not a valid attribute parameter type".
Why is that not allowed? I understand that fundamentally it just isn't on the list of accepted types. The valid types seem to be primitives, enums, string, type, and one dimensional arrays of the preceding types.
Is this just an old rule that did not get updated when Nullable came along?
解决方案Hungry? is equal to Nullable<Hungry>, which in terms mean that
[Hunger(NullableHungerLevel = Hungry.CouldEatMySocks)]is equal to
[Hunger(NullableHungerLevel = new Nullable<Hungry>(Hungry.CouldEatMySocks))]Since you can only use constant values in named attribute arguments you will have to resort to Shimmy's solution.
更多推荐
为什么是 Nullable<T>当 T 是时不是有效的自定义属性参数?
发布评论