为什么是 Nullable<T>当 T 是时不是有效的自定义属性参数?

编程入门 行业动态 更新时间:2024-10-17 05:30:56
本文介绍了为什么是 Nullable<T>当 T 是时不是有效的自定义属性参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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 Thing1

but I can't do this

[Hunger(NullableHungerLevel = Hungry.CouldEatMySocks)] public class Thing2

It 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&lt;T&gt;当 T 是时不是有效的自定义属性参数?

本文发布于:2023-11-02 14:16:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   属性   参数   是时   为什么是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!