
int number = 123;0x或0X开头,后面跟着0到9的数字以及A到F(或a到f)的字母。例如:int hexNumber = 0x7b; //相当于十进制的1230开头,后面跟着0到7的数字。例如:int octalNumber = 0173; //173相当于十进制的1230b或0B开头,后面跟着0和1的数字。例如:int binaryNumber = 0b1111011; // 相当于十进制的1233.14159 /* 合法 */314159E-5L /* 合法 */510E /* 非法:不完全指数 */210f /* 非法:没有小数或指数 */.e55 /* 非法:缺少整数或小数 */
字符串常量是括在双引号 ""里,或者是括在 @""里。字符串常量包含的字符与字符常量相似,可以是:普通字符、转义序列和通用字符
使用字符串常量时,可以把一个很长的行拆成多个行,可以使用空格分隔各个部分。
这里是一些字符串常量的实例。下面所列的各种形式表示相同的字符串。
string a = "hello, world"; // hello, worldstring b = @"hello, world"; // hello, worldstring c = "hello \t world"; // hello worldstring d = @"hello \t world"; // hello \t worldstring e = "Joe said \"Hello\" to me"; // Joe said "Hello" to mestring f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to mestring g = "\\\\server\\share\\file.txt"; // \\server\share\file.txtstring h = @"\\server\share\file.txt"; // \\server\share\file.txt
const <data_type> <constant_name> = value;using System;public class ConstTest{class SampleClass{public int x;public int y;public const int c1 = 5;public const int c2 = c1 + 5;publicSampleClass(int p1, int p2){x = p1;y = p2;}}staticvoidMain(){SampleClass mC = new SampleClass(11, 22);Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);Console.WriteLine("c1 = {0}, c2 = {1}",SampleClass.c1, SampleClass.c2);}}
x = 11, y = 22c1 = 5, c2 = 10
一个变量只不过是一个供程序操作的存储区的名字。
在 C# 中,变量是用于存储和表示数据的标识符,在声明变量时,您需要指定变量的类型,并且可以选择性地为其分配一个初始值。
在 C# 中,每个变量都有一个特定的类型,类型决定了变量的内存大小和布局,范围内的值可以存储在内存中,可以对变量进行一系列操作。
<data_type> <variable_list>;在这里,data_type 必须是一个有效的 C# 数据类型,可以是 char、int、float、double 或其他用户自定义的数据类型。variable_list 可以由一个或多个用逗号分隔的标识符名称组成。
一些有效的变量定义如下所示:
int i, j, k;char c, ch;float f, salary;double d;
int i = 100;在 C# 中,变量的命名需要遵循一些规则:
int myVariable = 10;string _userName = "John";
variable_name = value;<data_type> <variable_name> = value;int d = 3, f = 5; /* 初始化 d 和 f. */byte z = 22; /* 初始化 z. */double pi = 3.14159; /* 声明 pi 的近似值 */char x = 'x'; /* 变量 x 的值为 'x' */
using System;namespace VariableDefinition{class Program{staticvoidMain(string[] args){short a;int b ;double c;/* 实际初始化 */a = 10;b = 20;c = a + b;Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);Console.ReadLine();}}}
a = 10, b = 20, c = 30int num;num = Convert.ToInt32(Console.ReadLine());
C# 中的两种表达式:
lvalue:lvalue 表达式可以出现在赋值语句的左边或右边。
rvalue:rvalue 表达式可以出现在赋值语句的右边,不能出现在赋值语句的左边。
变量是 lvalue 的,所以可以出现在赋值语句的左边。数值是 rvalue 的,因此不能被赋值,不能出现在赋值语句的左边。下面是一个有效的语句:
int g = 20;10 = 20;