在属性构造函数或属性可空INT [英] Nullable int in Attribute Constructor or Property

查看:197
本文介绍了在属性构造函数或属性可空INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个自定义属性,我们称之为 MyCustomAttribute ,其中有像这样的构造:

So I have a custom attribute, let's call it MyCustomAttribute, which has a constructor like so:

public MyCustomAttribute(int? i)
{
   // Code goes here
}

和声明了一个属性:

public int? DefaultProperty { get; set; }

现在,我需要在<$ C通$ C> INT 或,以及这就是我所期待的。

Now if I wanted to use the property, I'd need to pass in an int or null, well that's what I'd expect.

但是,这给出了一个编译器错误:

But this gives a compiler error:

[MyCustomAttribute(1, DefaultProperty = 1)]
public int? MyProperty { get; set; }



也是如此这样的:

and so does this:

[MyCustomAttribute(null,DefaultProperty = null)]
public int? MyProperty { get; set; }



该错误是:的属性参数必须是常量表达式的typeof属性参数类型的表达式或数组创建表达式的构造和性能两者。

这是为什么?如果我改变了构造函数取一个int,我可以在 0 通过,但并不,它那种失败值的目的(这有时可以为null)

Why is this? If I change the constructor to take an int, I can pass in 0, but not null, which sort of defeats the purpose of the value (which can sometimes be null)

推荐答案

之所以说是同时兼具 0 是不变的初始化构造函数的参数实际需要的表达是没有的。这都需要一个转换是一个有效的 INT?的表达。在它本质上会生成以下

The reason why is that while both 0 and null are constant the actual expression needed to initialize the constructor parameter is not. Both require a conversion to be a valid int? expression. Under the hood it essentially generates the following

[MyCustomAttribute(new Nullable<int>(0))]

这表情不是常数不合法的,因为一个属性参数

This expression not being constant is not legal as an attribute argument

修改

DTB问,如果这是属性值非法为什么是合法的有一个可空参数的默认参数?

dtb asked if this is illegal in attribute values why is it legal to have a default parameter for a nullable parameter?

void Example(int? x = null);

您需要考虑的是谁/什么解释值是什么。

What you need to consider is who / what is interpreting the values.

有关的属性参数的值是由CLR解释。有关法律属性值的规则还没有真正从1.0变化。可空不存在,那么因此CLR不明白为空的初始化模式。

For attributes arguments the value is interpreted by the CLR. The rules concerning legal attribute values haven't really changed since 1.0. Nullable didn't exist then hence the CLR doesn't understand nullable initialization patterns.

有关默认参数的vaule由编译器在方法调用点解释。编译器理解为空的值,并有一点更多的空间,因为它可以根据IL值调用点创建非常量表达式工作。

For default arguments the vaule is interpreted by the compiler at the call site of the method. The compilers understands nullable values and has a bit more room to work with as it can create non-constant expressions at the call site based on the values in IL.

它是如何实际工作虽然?首先,编译器将实际编码常量和不同的方式在IL

How does it actually work though? First the compiler will actually encode constants and null differently in IL

// x = 0 
[DefaultParameterValue(0)]
// x = null
[DefaultParameterValue(null)]

在调用点,编译器检查这些值,并且为参数值合适的(非恒定)的表达。

At the call site the compiler examines these values and creates the appropriate (non-constant) expression for the parameter value.

这篇关于在属性构造函数或属性可空INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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