Why is a Nullablelt;Tgt; not a valid Custom Attribute Parameter when T is?(为什么是 Nullablelt;Tgt;当 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<T>当 T 是时不是有效的自定义属性参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么是 Nullable<T>当 T 是时不是有效的自定义属性参数?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01