如何在 Visual C# 中像 C 中的 #define 一样定义常量?
在 C 中,您可以定义这样的常量
#define NUMBER 9
,以便程序中出现的任何 NUMBER 都会被替换为 9。但 Visual C# 不会这样做。它是如何完成的?
In C you can define constants like this
#define NUMBER 9
so that wherever NUMBER appears in the program it is replaced with 9. But Visual C# doesn't do this. How is it done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要将其放在某个类中,用法为
ClassName.NUMBER
You'd need to put it in a class somewhere, and the usage would be
ClassName.NUMBER
您无法在 C# 中执行此操作。请改用
const int
。You can't do this in C#. Use a
const int
instead.查看 MSDN 上的如何:在 C# 中定义常量:
Check How to: Define Constants in C# on MSDN:
C语言中:
#define
(例如#define counter 100)汇编语言中:equ(例如counter equ 100)
C#语言中:< a href="https://msdn.microsoft.com/en-us/library/yt3yck0x.aspx" rel="nofollow noreferrer">根据 msdn 参考:
您可以使用#define 来定义符号。当您使用该符号作为传递给
#if
指令的表达式时,该表达式的计算结果将为 true,如以下示例所示:#define DEBUG
#define
指令不能用于声明常量值,这在 C 和 C++ 中通常是这样做的。 C# 中的常量最好定义为类或结构的静态成员。如果您有多个这样的常量,请考虑创建一个单独的“常量”类来保存它们。in c language:
#define
(e.g. #define counter 100)in assembly language: equ (e.g. counter equ 100)
in c# language: according to msdn refrence:
You use
#define
to define a symbol. When you use the symbol as the expression that's passed to the#if
directive, the expression will evaluate to true, as the following example shows:# define DEBUG
The
#define
directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.在 C# 中,根据 MSDN 库,我们有“const”关键字,它可以完成其他语言中“#define”关键字的工作。
“...当编译器在 C# 源代码中遇到常量标识符(例如,月份)时,它会将文字值直接替换为它生成的中间语言 (IL) 代码。”
(https://msdn.microsoft.com/en-us/library/ms173119。 aspx )
在声明时初始化常量,因为没有更改它们。
In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.
"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces."
( https://msdn.microsoft.com/en-us/library/ms173119.aspx )
Initialize constants at time of declaration since there is no changing them.
什么是“Visual C#”?没有这样的事情。只是 C# 或 .NET C# :)
另外,Python 的常量约定
CONSTANT_NAME
在 C# 中并不常见。我们通常根据MSDN标准使用CamelCase,例如public const string ExtractedMagicString = "vs2019";
What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)
Also, Python's convention for constants
CONSTANT_NAME
is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g.public const string ExtractedMagicString = "vs2019";