C#常量类型

C#常量类型 首页 / C#入门教程 / C#常量类型

常量指的是程序在执行期间不能更改的固定值,常量可以是任何基本数据类型,如整数常量、浮动常量、字符常量或字符串,还有枚举常量。

整数字面量

整数可以是十进制或十六进制常量,前缀指定基数或基数: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 . . . 十六进制的一位或多位数字

以下示例显示了几个转义序列字符-

using System;

namespace EscapeChar {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello\tWorld\n\n");
         Console.ReadLine();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Hello   World

字符串字面量

字符串文字或常量用双引号“”或@“”,字符串包含与字符文字相似的字符:纯字符,转义序列和通用字符。

以下是字符串文字的一些示例,这三种形式都是相同的字符串。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/csharp-constants.html

来源:LearnFk无涯教程网

"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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

Python实战 · 从0到1搭建直播视频平台 -〔Barry〕

eBPF核心技术与实战 -〔倪朋飞〕

性能优化高手课 -〔尉刚强〕

etcd实战课 -〔唐聪〕

微信小程序全栈开发实战 -〔李艺〕

Flutter核心技术与实战 -〔陈航〕

程序员的数学基础课 -〔黄申〕

代码精进之路 -〔范学雷〕

微服务架构实战160讲 -〔杨波〕

好记忆不如烂笔头。留下您的足迹吧 :)