在学习一门编程语言时,变量与类型是最基础也最重要的内容之一。在C#中,变量用于存储数据,而类型决定了变量能存储什么样的数据。接下来我们就来详细看看C#的变量与类型有哪些规则。
一、什么是变量
变量可以理解为一块带有名字的内存空间,程序运行时可以把数据存进去,也可以修改它的值。
例如:
cs
int number;
string title;
double price;
这些都只是声明变量,还没有赋值。
cs
int number = 10;
string title = "C#入门";
double price = 99.5;
这就是赋值,就是给变量一个具体的值。
当然你也可以先声明,再赋值:
cs
int number;
number = 10;
二、类型
C#是强类型语言,这意味着每个变量都必须有明确的类型,不同类型之间不能随意混用。
例如:
cs
int age = 20;
// age = "twenty"; //这是错误的,不能把字符串赋值给int
2.1常见的数据类型
C#的类型可分为两类:
- 值类型:(值类型直接保存实际数据)
整数类型:int、long、short、byte
浮点类型:float、double
高精度小数:decimal
布尔类型:char
结构体:struct
枚举:enum
- 引用类型:(保存的不是对象本身,而是对象的引用)
string、数组、类、接口、委托、object
2.2值类型-整数类型
int是最常用的整数类型,表示32位有符号整数。
cs
int age = 20;
int score = 100;
其他整数类型
cs
byte level = 255; //0-255
short year = 2026; //较小的数值范围
long population = 8000000000L; //长整数,后面通常加L
2.3值类型-浮点类型
float单精度浮点数,适合一般小数计算。
cs
float height = 175.5f; //float字面量后面需要加f或F
double双精度浮点数,是C#中最常用的小数类型
cs
double weight = 65.8;
double pi = 3.1415926;
decimal用于高精度计算,尤其适合金额、财务数据。
cs
decimal price = 199.99m;
decimal total = 100.50m; //decimal字面量后面需要加m或M
2.4值类型-布尔类型
bool只有两个值:true、false。常用于条件判断和if结合使用
cs
bool isStudent = true;
bool hasFinished = false;
2.5值类型-字符类型
char用于存储单个字符,使用单引号
cs
char grade = 'A';
char gender = '男';
2.6引用类型-string
string是C#中最常见的引用类型之一,用于保存文本。
cs
string name = "Alice";
string message = "你好";
字符串也可以拼接
cs
string firstName = "Zhang";
string lastName = "San";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
也可以使用字符串插值(这也是C#常用的写法)
cs
int age = 20;
string info = $"我今年{age}岁";
Console.WriteLine(info);
2.7引用类型-object
object是C#中所有类型的基类,也就是说,任何类型的值都可以赋给object。
cs
object a = 10;
object b = "hello";
object c = true;
不过使用object时通常需要进行类型转换,使用不当会降低代码的可读性和安全性。
(数组、类、接口、委托)后续单独介绍,这部分比较复杂。
三、变量命名规则
在C#中,变量命名需要遵循以下规则:
3.1必须以字母、下划线_或@开头
合法示例:
cs
int age;
int _count;
int @class;
非法示例:
cs
//int 1lage; //不能以数字开头
3.2变量名不能包含空格或特殊符号
错误示例:
cs
// string user name; //错误
3.3不能使用关键字作为变量名(除非加@)
例如:
cs
int @int = 10; //语法上可以,但是不建议这样写.
四、变量初始化
在C#中,局部变量在使用前必须先赋值,否则会报错
错误示例:
cs
int number;
// Console.WriteLine(number); // 错误:未赋值
正确示例:
cs
int number = 0;
Console.WriteLine(number);
五、类型推断
C#支持使用var进行类型推断
cs
var age = 18; //var会自动推断出age是int
var name = "Tom"; //var会自动推断出name是string
var price = 19.9; //var会自动推断出price是double
注意:var并不表示"没有类型",它只是让编译器自动推断类型。一旦推断完成,类型就固定了。
例如:
cs
var number = 10;
// number = "hello"; // 错误,number 实际上是 int
什么时候适合使用var?
当右侧类型明显、类型名称过长、使用匿名类型
例如:
cs
var student = new { Name = "Tom", Age = 20 };
不太适合:
右侧表达式不明显,影响可读性时:
cs
var x = GetData(); // 如果不知道 GetData 返回什么,会不利于阅读
六、常量
如果某个值在程序运行过程中不会改变,可以使用常量。
cs
const double PI = 3.1415926;
const string SchoolName = "ABC School";
常量的特点是:声明时必须赋值、之后不能再修改。
错误示例:
cs
const int Max = 100;
// Max = 200; // 错误,常量不能修改
七、类型转换
在实际开发过程中,经常需要在不同类型之间进行转换。C#有两种类型转换方式:隐式类型转换、显式类型转换。
7.1隐式类型转换
当转换安全且不会丢失数据时,C#会自动完成转换。
cs
int num = 100;
double d = num; // int 自动转换为 double
Console.WriteLine(d);
7.2显示类型转换
如果转换可能丢失数据,就需要手动强制转换。
cs
double d = 3.14;
int num = (int)d;
Console.WriteLine(num); // 输出 3,这里的小数部分就被截断了
7.3使用Convert
Convert类可以将字符串等类型转换为其他类型。
cs
string strAge = "25";
int age = Convert.ToInt32(strAge);
Console.WriteLine(age);
7.4使用Parse
cs
string strNumber = "123";
int number = int.Parse(strNumber);
Console.WriteLine(number);
如果字符串格式不正确,会抛出异常。
7.5使用TryParse
相比7.4的parse更安全的是使用TryParse(目前看不懂没关系,先去看后面的知识点)
cs
string input = "123";
if (int.TryParse(input, out int result))
{
Console.WriteLine($"转换成功:{result}");
}
else
{
Console.WriteLine("转换失败");
}
这是实际开发中更推荐的方式。
八、空值与可空类型
值类型默认不能为null,但有时候我们需要表示"这个值暂时不存在",这时就可以使用可空值类型。
cs
int? age = null;
double? score = 95.5;
bool? isPassed = null;
这里的int? 实际上是Nullable<int>的简写形式。
判断是否有值:
cs
int? age = null;
if (age.HasValue)
{
Console.WriteLine(age.Value);
}
else
{
Console.WriteLine("age 目前没有值");
}
九、默认值
C#中不同类型有默认值的概念。常见的默认值如下:
cs
int -> 0
double ->0.0
bool ->false
char ->'\0'
引用类型(如string ) -> null
这些都可以通过default关键字获取
cs
int a = default;
bool b = default;
string s = default;
Console.WriteLine(a); // 0
Console.WriteLine(b); // False
Console.WriteLine(s); // null
十、小案例
下面是一个输入输出的案例程序,你可以手动敲一遍
cs
using System;
class Program
{
static void Main()
{
Console.Write("请输入你的姓名:");
string name = Console.ReadLine();
Console.Write("请输入你的年龄:");
string ageInput = Console.ReadLine();
if (int.TryParse(ageInput, out int age))
{
Console.WriteLine($"你好,{name},你今年 {age} 岁。");
}
else
{
Console.WriteLine("年龄输入格式不正确。");
}
}
}
这个程序里的string 用于接收输入,Console.ReadLine()获取输入的字符串,然后用int.TryParse()将字符串安全的转换为整数,最后用Console.WriteLine()输出结果。
十一、总结
C#中的变量与类型是后续学习所有内容的基础。掌握这部分内容之后,你才能更好学习理解后续的内容。
十二、参考链接
有些地方介绍的不详细,可以参考微软提供的学习指南。
1. C# 类型和变量总览
- Microsoft Learn:Types and variables in C#
https://learn.microsoft.com/dotnet/csharp/tour-of-csharp/tutorials/
2. C# 内置类型
- Microsoft Learn:Built-in types (C# reference)
https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/built-in-types
3. 变量
- Microsoft Learn:Variables - C# language specification / reference related content
https://learn.microsoft.com/dotnet/csharp/language-reference/
4. 数值类型
-
Microsoft Learn:Integral numeric types
https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/integral-numeric-types -
Microsoft Learn:Floating-point numeric types
https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types
5. 字符串
- Microsoft Learn:String (C# reference)
https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/reference-types
6. 类型转换
- Microsoft Learn:Casting and type conversions
https://learn.microsoft.com/dotnet/csharp/programming-guide/types/casting-and-type-conversions
7. 可空值类型
- Microsoft Learn:Nullable value types
https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/nullable-value-types