为什么一个可空< T>不是有效的自定义属性参数当T? [英] Why is a Nullable<T> not a valid Custom Attribute Parameter when T is?

查看:131
本文介绍了为什么一个可空< T>不是有效的自定义属性参数当T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个这样的枚举

If I have an enum like this

public enum Hungry
{
    Somewhat,
    Very,
    CouldEatMySocks
}

和这样的自定义属性

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

它会产生一个错误,指出'NullableHungerLevel'不是一个有效的命名属性的参数,因为它不是一个有效的属性参数类型。

It generates an error that says "'NullableHungerLevel' is not a valid named attribute argument because it is not a valid attribute parameter type".

这是为什么不允许?据我所知,从根本上它只是不接受的类型的列表上。有效的类型似乎是原语,枚举,字符串类型和preceding类型的一维数组。

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)]

等于

[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.

这篇关于为什么一个可空&LT; T&GT;不是有效的自定义属性参数当T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆