C#之语法变量、弹窗显示、注释
03C#之语法变量、弹窗显示、注释
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 第一个winform项目
{
public partial class Form1 : Form
{
// 注释:不启用代码,只能用来看,用作说明
// 程序中存储和操作数据,需要变量
// 位置就在这里定义,不要变
// 怎么写:数据类型 变量名 = 初始值;
int age = 25;
string name = "张三";
double price = 19.99;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("浮点数:"+ price);
MessageBox.Show("字符串:" + name);
MessageBox.Show("整数:" + age);
}
}
}
变量是编程中最基本的概念之一,它允许我们在程序中存储和操作数据。
1. 变量基础
1.1 什么是变量?
变量是程序中用于存储数据的命名容器。每个变量都有:
- 名称(标识符)
- 数据类型
- 值
1.2 基本语法
数据类型 变量名 = 初始值;
示例:
int age = 25;
string name = "张三";
double price = 19.99;
bool isTrue = true;
2. 数据类型
C#是强类型语言,变量必须声明其数据类型。主要数据类型分为:
2.1 值类型
类型 | 描述 | 示例 |
---|---|---|
int | 32位有符号整数 | int count = 10; |
double | 64位双精度浮点数 | double pi = 3.14159; |
float | 32位单精度浮点数 | float f = 1.23f; |
decimal | 高精度十进制数(适合财务计算) | decimal money = 100.50m; |
char | 单个Unicode字符 | char grade = 'A'; |
bool | 布尔值(true/false) | bool isActive = true; |
byte | 8位无符号整数(0-255) | byte b = 255; |
enum | 枚举类型 | enum Day { Mon, Tue } |
struct | 值类型结构体 | 自定义结构体 |
2.2 引用类型
类型 | 描述 | 示例 |
---|---|---|
string | Unicode字符串 | string message = "Hello"; |
class | 引用类型类 | 自定义类 |
interface | 接口 | 自定义接口 |
array | 数组 | int[] numbers = {1,2,3}; |
object | 所有类型的基类 | object obj = "anything"; |
dynamic | 动态类型(编译时类型检查关闭) | dynamic dyn = 10; |
3. 变量声明与初始化
3.1 声明变量
// 声明但不初始化
int number;
string text;
// 声明并初始化
int count = 0;
string name = "C#教程";
3.2 隐式类型变量(var)
C#允许使用var
关键字让编译器自动推断类型:
var message = "Hello World"; // 编译器推断为string
var count = 100; // 编译器推断为int
var price = 9.99m; // 编译器推断为decimal
注意:var
不是类型,只是编译器的语法糖,变量在编译时仍会被赋予具体类型。
3.3 空值处理(nullable类型)
值类型默认不能为null,但可以使用?
或Nullable<T>
使其可为null:
int? nullableInt = null; // 或 Nullable<int> nullableInt = null;
bool? isAvailable = null;
// 使用示例
if (nullableInt.HasValue)
{
Console.WriteLine($"值是: {nullableInt.Value}");
}
else
{
Console.WriteLine("值为null");
}
// 使用空合并运算符 ?? 提供默认值
int defaultValue = nullableInt ?? 0; // 如果nullableInt为null,则使用0
4. 变量作用域
4.1 局部变量
在方法或代码块中声明的变量:
void ExampleMethod()
{
int localVar = 10; // 局部变量,仅在此方法内有效
if (true)
{
int blockVar = 20; // 代码块内变量,仅在此块内有效
Console.WriteLine(blockVar);
}
// Console.WriteLine(blockVar); // 编译错误:blockVar在此作用域不可见
Console.WriteLine(localVar);
}
4.2 字段(成员变量)
在类中声明的变量:
class Person
{
// 字段(实例变量)
private string _name;
private int _age;
// 构造函数
public Person(string name, int age)
{
_name = name;
_age = age;
}
// 方法
public void Introduce()
{
Console.WriteLine($"我叫{_name},今年{_age}岁");
}
}
4.3 静态变量
使用static
关键字声明的变量,属于类而非实例:
class Counter
{
public static int TotalCount = 0; // 静态变量
public Counter()
{
TotalCount++; // 每次创建实例时增加计数
}
}
// 使用
Counter c1 = new Counter();
Counter c2 = new Counter();
Console.WriteLine(Counter.TotalCount); // 输出2
5. 常量与只读字段
5.1 常量(const)
在编译时确定的不可变值:
class MathConstants
{
public const double PI = 3.141592653589793;
public const int MaxValue = 100;
}
// 使用
double area = MathConstants.PI * 5 * 5;
特点:
- 必须在声明时初始化
- 只能是基本类型或字符串
- 隐式为static
- 编译时替换为实际值
5.2 只读字段(readonly)
在声明时或构造函数中初始化的不可变字段:
class Person
{
public readonly string BirthDate; // 可以在声明时初始化
public Person(string name, string birthDate)
{
Name = name;
BirthDate = birthDate; // 或在构造函数中初始化
}
public string Name { get; set; }
}
// 使用
var person = new Person("李四", "1990-01-01");
// person.BirthDate = "2000-01-01"; // 编译错误:只读字段不能修改
特点:
- 可以在声明时或构造函数中初始化
- 适用于需要运行时确定的不可变值
- 不是static的,每个实例有自己的副本
6. 变量默认值
未初始化的变量有默认值:
类型 | 默认值 |
---|---|
数值类型 | 0 或 0.0 |
char | ‘\0’ |
bool | false |
引用类型 | null |
int uninitializedInt;
Console.WriteLine(uninitializedInt); // 输出0
string uninitializedString;
Console.WriteLine(uninitializedString == null); // 输出True
7. 类型转换
7.1 隐式转换
当不会丢失数据时自动进行:
int i = 100;
long l = i; // 隐式转换
float f = 3.14f;
double d = f; // 隐式转换
7.2 显式转换(强制转换)
当可能丢失数据时需要显式转换:
double d = 10.5;
int i = (int)d; // 显式转换,结果为10(小数部分丢失)
// 危险示例 - 可能溢出
long l = long.MaxValue;
int i2 = (int)l; // 可能得到负数
7.3 使用Convert类
string str = "123";
int num = Convert.ToInt32(str); // 字符串转整数
bool b = Convert.ToBoolean("True"); // 字符串转布尔
7.4 使用Parse和TryParse方法
string str = "456";
int number = int.Parse(str); // 成功时返回int,失败时抛出异常
// 更安全的TryParse方法
string input = "not a number";
if (int.TryParse(input, out int result))
{
Console.WriteLine($"转换成功: {result}");
}
else
{
Console.WriteLine("转换失败");
}
7.5 使用checked和unchecked
控制整数运算的溢出检查:
int max = int.MaxValue;
// checked - 启用溢出检查(默认在调试模式下启用)
checked
{
int overflow = max + 1; // 抛出OverflowException
}
// unchecked - 禁用溢出检查(默认在发布模式下)
unchecked
{
int overflow = max + 1; // 静默溢出,结果为int.MinValue
}
8. 变量最佳实践
-
使用有意义的名称:
// 不好的命名 int a = 10; string s = "Hello"; // 好的命名 int studentCount = 10; string greetingMessage = "Hello";
-
遵循命名约定:
- 局部变量和参数:camelCase(
studentName
) - 公共字段和属性:PascalCase(
StudentName
) - 私有字段:
_camelCase
(_studentName
) - 常量:PascalCase(
MaxStudentCount
)
- 局部变量和参数:camelCase(
-
避免魔法数字:
// 不好的做法 if (age > 18) { /* ... */ } // 好的做法 const int AdultAge = 18; if (age > AdultAge) { /* ... */ }
-
限制变量作用域:
- 只在需要时声明变量
- 尽早初始化变量
- 避免在循环外声明只在循环内使用的变量
-
考虑使用var的场景:
- 当类型明显时(如
var list = new List<string>();
) - 避免在类型不明确时使用(如
var x = GetValue();
)
- 当类型明显时(如
9. 高级主题
9.1 动态类型(dynamic)
dynamic dynamicVar = 10;
Console.WriteLine(dynamicVar.GetType()); // System.Int32
dynamicVar = "Hello";
Console.WriteLine(dynamicVar.GetType()); // System.String
// 动态调用方法(即使不存在)
dynamicVar.NonExistentMethod(); // 运行时抛出异常
注意:动态类型会关闭编译时类型检查,应谨慎使用。
9.2 局部函数中的变量捕获
void OuterMethod()
{
int outerVar = 10;
void LocalFunction()
{
Console.WriteLine(outerVar); // 捕获外部变量
}
LocalFunction(); // 输出10
}
9.3 ref和out参数
// ref参数 - 必须先初始化
void ModifyValue(ref int x)
{
x = x * 2;
}
int num = 5;
ModifyValue(ref num);
Console.WriteLine(num); // 输出10
// out参数 - 不需要初始化,方法必须赋值
void GetValue(out int result)
{
result = 42;
}
int value;
GetValue(out value);
Console.WriteLine(value); // 输出42
9.4 in参数(C# 7.2+)
// in参数 - 只读引用传递,避免值类型的拷贝
void PrintArray(in int[] array)
{
// array[0] = 10; // 编译错误:不能修改
Console.WriteLine(array.Length);
}
int[] numbers = { 1, 2, 3 };
PrintArray(in numbers);
10. 总结
本教程涵盖了C#中变量的主要概念和使用方法:
- 变量是存储数据的容器,有名称、类型和值
- C#是强类型语言,变量必须声明类型
- 值类型和引用类型有不同的行为
- 变量有不同作用域(局部、字段、静态)
- 常量和只读字段用于不可变值
- 提供了多种类型转换方法
- 遵循变量命名的最佳实践
- 高级特性包括动态类型、变量捕获和参数修饰符