在属性中使用int常量 [英] Use int constant in attribute

查看:88
本文介绍了在属性中使用int常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么我不能在C#属性中使用const Int32吗?

Can anybody explain why I can't use a const Int32 in an C# attribute?

示例:

private const Int32 testValue = 123;  
[Description("Test: " + testValue)]  
public string Test { get; set; }

使编译器说:


属性参数必须是一个常量表达式,...

"An attribute argument must be a constant expression, ..."

为什么?

推荐答案

由于错误状态,属性参数必须是恒定表达式。

As the error states, an attribute argument must be a constant expression.

连接字符串和整数不是常量表达式。

Concatenating a string and an integer is not a constant expression.

因此,如果您通过 Test: + 123 ,它将给出相同的错误。
另一方面,如果将 testValue 更改为字符串,它将进行编译。

Thus, if you pass "Test: " + 123 directly, it will give the same error. On the other hand, if you change testValue to a string, it will compile.

常量表达式的规则规定,只要两个操作数本身都是常量表达式,常量表达式就可以包含算术运算符。

The rules for constant expressions state that a constant expression can contain arithmetic operators, provided that both operands are themselves constant expressions.

因此, A + B 仍为常数。

但是, A + 1 使用 string运算符+(string x,object y); ,其中将整数操作数装箱到对象上。 >
常量表达式规则明确指出

However, "A" + 1 uses the string operator +(string x, object y);, in which the integer operand is boxed to an object.
The constant-expression rules explicitly state that


其他转换(包括装箱,拆箱和非空值的隐式引用转换)不允许在常量表达式。

Other conversions including boxing, unboxing and implicit reference conversions of non-null values are not permitted in constant expressions.

这篇关于在属性中使用int常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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