常量指的是程序在执行期间不能更改的固定值,常量可以是任何基本数据类型,如整数常量、浮动常量、字符常量或字符串,还有枚举常量。
整数可以是十进制或十六进制常量,前缀指定基数或基数:0x或0x表示十六进制,没有前缀id表示十进制。
整数还可以有一个后缀,该后缀是U和L的组合,分别表示无符号和长,后缀可以是大写或小写,并且可以是任意顺序。
以下是整型文字-的一些示例
212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */
以下是各种类型的整数文字-的其他示例
85 /* decimal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
浮点数有一个整数部分,一个小数点,您可以十进制形式或指数形式表示浮点数,以下是浮点数-的一些示例
3.14159 /* Legal */ 314159E-5F /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */
字符用单引号括起来,如,‘x',可以存储在char类型的简单变量中。
在C#中,当某些字符前面有一个反斜杠时,它们有特殊的含义,它们被用来像newline()或tab()一样表示。
Escape sequence | Meaning |
---|---|
\\ | \反斜线 |
\' | '单引号 |
\" | "双引号 |
\? | ?问号 |
\a | 警报或铃声 |
\b | 退格键 |
\f | 换页 |
\n | 换行 |
\r | 回车 |
\t | 水平Tab |
\v | 垂直Tab |
\xhh . . . | 十六进制的一位或多位数字 |
以下示例显示了几个转义序列字符-
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/csharp-constants.html
来源:LearnFk无涯教程网
using System; namespace EscapeChar { class Program { static void Main(string[] args) { Console.WriteLine("Hello\tWorld\n\n"); Console.ReadLine(); } } }
编译并执行上述代码时,将生成以下输出-
Hello World
字符串文字或常量用双引号“”或@“”,字符串包含与字符文字相似的字符:纯字符,转义序列和通用字符。
以下是字符串文字的一些示例,这三种形式都是相同的字符串。
"hello, dear" "hello,\ dear" "hello, " "d" "ear" @"hello dear"
使用const关键字定义常量,用于定义常量的语法是-
const <data_type> <constant_name>=value;
下面的程序演示如何在程序-中定义和使用常量
using System; namespace DeclaringConstants { class Program { static void Main(string[] args) { const double pi = 3.14159; //constant declaration double r; Console.WriteLine("Enter Radius: "); r = Convert.ToDouble(Console.ReadLine()); double areaCircle = pi * r * r; Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle); Console.ReadLine(); } } }
编译并执行上述代码时,将生成以下输出-
Enter Radius: 3 Radius: 3, Area: 28.27431
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)