Use int constant in attribute(在属性中使用 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, ..."
为什么?
推荐答案
由于错误状态,属性参数必须是 constant 表达式.
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" 仍然是不变的.
Therefore, "A" + "B" is still constant.
但是,A";+ 1 使用字符串运算符+(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 常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在属性中使用 int 常量
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
