C# 基础知识详解
C# 基础知识详解
开发环境安装
推荐使用 Visual Studio 进行开发环境的安装与配置。
using System;
namespace Lesson1_Exercises
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lesson1_Exercises Explanation");
// Console.Write(""); // Print without a newline
// Console.WriteLine(""); // Print with a newline
// Console.ReadKey(); // Wait for a single key press
// Console.ReadLine(); // Wait for Enter key press to end input
// Console.WriteLine("Please enter username:");
// Console.ReadLine();
// Console.WriteLine("Please enter age:");
// Console.ReadLine();
// Console.WriteLine("Please enter class:");
// Console.ReadLine();
// Console.WriteLine("What is your favorite sport?");
// Console.ReadLine();
// Console.WriteLine("Haha, what a coincidence, I like that sport too!");
Console.WriteLine("**********");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("**********");
Console.Write("**********");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("* *");
Console.WriteLine();
Console.Write("**********");
}
}
}
变量
变量是用于存储不同类型数据的容器。
变量类型
- 有符号整型:存储正负数及零。
sbyte: -128 到 127int: 约 -21 亿到 21 亿short: -32768 到 32767long: 约 -900 万兆到 900 万兆
- 无符号整型:存储零和正数。
byte: 0 到 255uint: 0 到约 42 亿ushort: 0 到 65535ulong: 0 到约 18 百万兆
- 特殊类型:
bool: 存储true或false。char: 存储单个字符 (例如'A')。string: 存储字符串 (例如"你好")。
- 浮点数:
float: 存储约 7-8 位有效数字,精度可能因编译器而异(四舍五入)。double: 存储约 15-17 位有效数字。decimal: 存储约 27-28 位有效数字,通常不推荐使用。
在 C# 中,浮点数默认被视为
double类型。为float变量赋值时,需要在数字后加上f后缀,以明确表示其类型并避免精度丢失。
变量必须先声明后使用,且不能在未声明的情况下直接修改。可以同时声明多个同类型变量:
int var1 = 2, var2 = 2, var3 = 3;
变量相关练习
Console.WriteLine("变量相关练习题");
#region 练习题1
// 以下代码的输出结果是?
double num = 36.6;
Console.WriteLine("num"); // 输出字符串 "num"
Console.WriteLine(num); // 输出变量 num 的值 36.6
#endregion
#region 练习题2
// 声明 float 类型变量时,为何要在数字后面加 f?
// 回答:因为 C# 默认浮点数是 double 类型,加 f 明确表示是 float 类型。
float floatVar = 1.234F;
decimal decVar = 1.2344545M;
#endregion
#region 练习题3
// 请定义一系列变量来存储你的名字、年龄、性别、身高、体重、家庭住址等,并打印出来。
string name = "示例姓名";
Console.WriteLine("我的名字是: " + name);
byte age = 18;
Console.WriteLine("我的年龄是: " + age);
float height = 177.5f;
Console.WriteLine("我的身高是: " + height);
float weight = 68.5f;
Console.WriteLine("我的体重是: " + weight);
string address = "某个地址";
Console.WriteLine("我的家庭住址是: " + address);
#endregion
#region 练习题4
// 小明的数学考试成绩是80,语文的考试成绩是78,英语的考试成绩是98,请用变量描述并打印。
byte mathScore = 80;
byte chineseScore = 78;
byte englishScore = 98;
Console.WriteLine("我的数学成绩是: " + mathScore);
Console.WriteLine("我的语文成绩是: " + chineseScore);
Console.WriteLine("我的英语成绩是: " + englishScore);
#endregion
Visual Studio 错误解决
当遇到类似"特性重复"的编译错误时,通常是由于AssemblyInfo.cs 文件中的程序集信息被重复定义。解决办法是编辑该文件,注释掉重复的 [assembly: ...] 属性。
// 在 AssemblyInfo.cs 文件中,找到并注释掉类似如下的行:
// [assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
注释掉重复的属性后,重新生成解决方案即可。
变量存储空间
可以使用 sizeof() 运算符(适用于值类型)来获取变量在内存中占用的字节数。
#region 变量存储空间
// 整型
int sbyteSize = sizeof(sbyte); Console.WriteLine($"sbyte: {sbyteSize} bytes");
int intSize = sizeof(int); Console.WriteLine($"int: {intSize} bytes");
int shortSize = sizeof(short); Console.WriteLine($"short: {shortSize} bytes");
int longSize = sizeof(long); Console.WriteLine($"long: {longSize} bytes");
// 无符号整型
int usbyteSize = sizeof(byte); Console.WriteLine($"byte: {usbyteSize} bytes");
int uintSize = sizeof(uint); Console.WriteLine($"uint: {uintSize} bytes");
int ushortSize = sizeof(ushort); Console.WriteLine($"ushort: {ushortSize} bytes");
int ulongSize = sizeof(ulong); Console.WriteLine($"ulong: {ulongSize} bytes");
// 浮点数
int floatSize = sizeof(float); Console.WriteLine($"float: {floatSize} bytes");
int doubleSize = sizeof(double); Console.WriteLine($"double: {doubleSize} bytes");
int decimalSize = sizeof(decimal); Console.WriteLine($"decimal: {decimalSize} bytes"); // 注意:sizeof 对 decimal 不直接支持,此处为示例,实际需注意
// 特殊类型
int boolSize = sizeof(bool); Console.WriteLine($"bool: {boolSize} bytes");
int charSize = sizeof(char); Console.WriteLine($"char: {charSize} bytes");
// sizeof 不能用于 string 类型,因为它是一个引用类型。
#endregion
变量的本质
变量的本质是计算机内存中的一个存储单元,它以二进制形式存储数据。计算机使用二进制是因为电子信号只有"开"和"关"两种状态,分别用 0 和 1 表示。最小的存储单位是 bit(位),8 个 bit 组成一个 byte(字节)。
变量命名规范
- 必须遵守的规则:
- 变量名不能重复。
- 变量名不能以数字开头。
- 变量名不能使用 C# 关键字。
- 变量名不能包含特殊符号(下划线
_除外)。
- 建议的命名规则:
- 驼峰命名法 (Camel Case):变量名以小写字母开头,后续每个单词的首字母大写(例如:
myVariableName)。 - 帕斯卡命名法 (Pascal Case):所有单词的首字母都大写(通常用于类名、方法名)(例如:
MyClassName)。
变量名应具有描述性,清晰地表达其用途。避免使用拼音或中文命名。
- 驼峰命名法 (Camel Case):变量名以小写字母开头,后续每个单词的首字母大写(例如:
常量
常量是其值在程序执行期间不能被修改的变量。使用 const 关键字声明。
using System;
namespace Lesson5_Constants
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("常量");
// 常量的声明和初始化
const int MAX_VALUE = 100;
const float PI = 3.1415926f;
Console.WriteLine($"最大值: {MAX_VALUE}");
Console.WriteLine($"圆周率: {PI}");
// 尝试修改常量会导致编译错误
// MAX_VALUE = 200; // Error: Cannot assign to variable 'MAX_VALUE' because it is a const field
}
}
}
常量必须在声明时初始化,且其值在程序运行时不可更改。常用于定义固定的、不变的值,如数学常数。
转义字符
转义字符用于在字符串中表示一些特殊的字符或控制符,以 \ 开头。
\': 单引号\": 双引号\\: 反斜杠\n: 换行\t: 制表符(Tab)\b: 退格\0: 空字符\a: 警报音
使用 @ 符号可以创建"逐字字符串",其中的转义字符将按字面意思解释。
using System;
namespace Lesson6_EscapeCharacters
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("转义字符");
// 使用转义字符
string message1 = "\'这是一个带单引号的字符串\'";
Console.WriteLine(message1);
string message2 = "\"这是一个带双引号的字符串\"";
Console.WriteLine(message2);
string message3 = "第一行\n第二行";
Console.WriteLine(message3);
string message4 = "文件路径: C:\\Program Files\\MyApp";
Console.WriteLine(message4);
string message5 = "项目\t名称";
Console.WriteLine(message5);
// 使用逐字字符串
string literalString = @"这是一个
逐字字符串,
可以包含 \n 和 """;
Console.WriteLine(literalString);
}
}
}
类型转换
隐式转换
隐式转换是指从一个范围较小(精度较低)的数据类型自动转换为范围较大(精度较高)的数据类型,无需显式声明。
规则:大范围可以装小范围。
- 整数类型(有符号与无符号之间):
int->long,uint->ulong, etc. - 浮点数与整数:
int->float,float->double。 decimal类型可以隐式转换为任何整数类型,但不能隐式从float或double转换。
特殊类型 bool、string 不参与隐式转换。char 可以隐式转换为整数和浮点类型。
总结:高精度(大范围)可隐式转换为低精度(小范围)。string 和 bool 不参与此规则。
显式转换(强制类型转换)
显式转换(强制类型转换)是将一个范围较大的数据类型强制转换为范围较小的数据类型。这可能导致数据丢失或精度降低。
语法:(目标类型)变量
using System;
namespace ExplicitConversion
{
class Program
{
static void Main(string[] args)
{
#region 强制转换
// 将高精度类型强制转换为低精度类型
// 语法:变量名 = (目标类型)变量;
int intValue = 128;
sbyte sbValue = (sbyte)intValue; // 可能会发生数据截断或溢出
Console.WriteLine($"int {intValue} to sbyte: {sbValue}"); // 输出可能不符合预期
double doubleValue = 123.45;
int intFromDouble = (int)doubleValue; // 舍弃小数部分
Console.WriteLine($"double {doubleValue} to int: {intFromDouble}"); // 输出 123
char charValue = 'A';
int asciiValue = (int)charValue; // 转换为ASCII码
Console.WriteLine($"char '{charValue}' to int: {asciiValue}"); // 输出 65
// bool 和 string 不能使用括号进行强制转换
#endregion
#region Parse 方法
// 将字符串转换为特定类型的数值
// 语法:目标类型.Parse(字符串)
// 字符串必须能被正确解析,否则会抛出异常。
string numberString = "456";
int parsedInt = int.Parse(numberString);
Console.WriteLine($"Parsed int: {parsedInt}");
// short sValue = short.Parse("123"); // OK
// byte bValue = byte.Parse("255"); // OK
// uint uValue = uint.Parse("4000000000"); // OK
// long lValue = long.Parse("9000000000000000000"); // OK
// float fValue = float.Parse("1.23f"); // OK
// double dValue = double.Parse("4.56"); // OK
// decimal mValue = decimal.Parse("7.89"); // OK
// int invalidParse = int.Parse("abc"); // Throws FormatException
#endregion
#region Convert 类
// 提供更全面的类型转换方法,包括从字符串、布尔值等。
// 语法:Convert.To目标类型(待转换值)
// 转换为整数
int convertedInt = Convert.ToInt32("789");
Console.WriteLine($"Convert to int: {convertedInt}");
convertedInt = Convert.ToInt32(98.76); // 四舍五入
Console.WriteLine($"Convert double to int: {convertedInt}");
// 转换为布尔值
bool boolTrue = Convert.ToBoolean("true");
bool boolFalse = Convert.ToBoolean("false");
Console.WriteLine($"Convert \"true\" to bool: {boolTrue}");
Console.WriteLine($"Convert \"false\" to bool: {boolFalse}");
// 转换为其他类型
sbyte sbConverted = Convert.ToSByte("10");
short shConverted = Convert.ToInt16("20");
long lgConverted = Convert.ToInt64("30");
byte btConverted = Convert.ToByte("40");
ushort ushConverted = Convert.ToUInt16("50");
uint uiConverted = Convert.ToUInt32("60");
ulong ulgConverted = Convert.ToUInt64("70");
float flConverted = Convert.ToSingle("8.8f");
double dbConverted = Convert.ToDouble("9.9");
decimal dcConverted = Convert.ToDecimal("10.1");
char chConverted = Convert.ToChar("X");
// 转换为字符串
string stringFromInt = Convert.ToString(123);
string stringFromDouble = Convert.ToString(4.56);
string stringFromBool = Convert.ToString(true);
Console.WriteLine($"Convert int 123 to string: {stringFromInt}");
Console.WriteLine($"Convert double 4.56 to string: {stringFromDouble}");
Console.WriteLine($"Convert bool true to string: {stringFromBool}");
#endregion
}
}
}
异常捕获
使用 try-catch-finally 块来处理可能发生的运行时错误(异常),防止程序崩溃。
try: 包含可能引发异常的代码。catch: 捕获并处理特定类型的异常。finally: 无论是否发生异常,都会执行的代码块,通常用于资源释放。
using System;
namespace ExceptionHandling
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入一个整数:");
string input = Console.ReadLine();
int number = int.Parse(input); // 可能抛出 FormatException
Console.WriteLine($"你输入的数字是: {number}");
int result = 10 / number; // 可能抛出 DivideByZeroException
Console.WriteLine($"10 / {number} = {result}");
}
catch (FormatException)
{
Console.WriteLine("输入格式错误,请输入有效的整数。");
}
catch (DivideByZeroException)
{
Console.WriteLine("除数不能为零。");
}
catch (Exception ex) // 捕获所有其他类型的异常
{
Console.WriteLine($"发生未知错误: {ex.Message}");
}
finally
{
Console.WriteLine("异常处理过程结束。");
}
}
}
}
运算符
算术运算符
用于执行数学计算。
+: 加法-: 减法*: 乘法/: 除法(整数除法会舍弃小数部分)%: 取余(模运算符)
复合赋值运算符:+=, -=, *=, /=, %= (例如 x += 5 等同于 x = x + 5)。
自增/自减运算符:++, -- (例如 x++, ++x)。前缀形式(++x)先自增再运算,后缀形式(x++)先运算再自增。
优先级:算术运算符有优先级,乘除取余优先于加减。括号 () 可改变运算优先级。
using System;
namespace ArithmeticOperators
{
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 3;
Console.WriteLine($"a + b = {a + b}"); // 13
Console.WriteLine($"a - b = {a - b}"); // 7
Console.WriteLine($"a * b = {a * b}"); // 30
Console.WriteLine($"a / b = {a / b}"); // 3 (整数除法)
Console.WriteLine($"a % b = {a % b}"); // 1 (余数)
// 复合运算符
a += b; // a = a + b;
Console.WriteLine($"a += b results in a = {a}"); // 16
// 自增/自减
int x = 5;
Console.WriteLine($"x++ (post-increment): {x++}"); // 输出 5, x 变为 6
Console.WriteLine($"After x++, x is: {x}"); // 输出 6
Console.WriteLine($"++x (pre-increment): {++x}"); // x 变为 7, 输出 7
Console.WriteLine($"After ++x, x is: {x}"); // 输出 7
// 优先级
int result = 5 + 3 * 2; // 5 + 6 = 11
Console.WriteLine($"5 + 3 * 2 = {result}");
result = (5 + 3) * 2; // 8 * 2 = 16
Console.WriteLine($"(5 + 3) * 2 = {result}");
}
}
}
条件运算符
用于比较两个值,返回一个布尔结果(true 或 false)。
>: 大于<: 小于==: 等于!=: 不等于>=: 大于等于<=: 小于等于
using System;
namespace ComparisonOperators
{
class Program
{
static void Main(string[] args)
{
int num1 = 15;
int num2 = 10;
bool isEqual = (num1 == num2);
Console.WriteLine($"num1 == num2: {isEqual}"); // false
bool isGreater = (num1 > num2);
Console.WriteLine($"num1 > num2: {isGreater}"); // true
bool isLessOrEqual = (num1 <= num2);
Console.WriteLine($"num1 <= num2: {isLessOrEqual}"); // false
// 浮点数比较
double d1 = 3.14;
double d2 = 3.14159;
Console.WriteLine($"d1 < d2: {d1 < d2}"); // true
}
}
}
逻辑运算符
用于组合布尔表达式。
&&(逻辑与): 只有当两个操作数都为true时,结果才为true。||(逻辑或): 只要有一个操作数为true,结果就为true。!(逻辑非): 对操作数的布尔值取反。
using System;
namespace LogicalOperators
{
class Program
{
static void Main(string[] args)
{
bool condition1 = true;
bool condition2 = false;
// 逻辑与 (&&)
Console.WriteLine($"true && false: {condition1 && condition2}"); // false
Console.WriteLine($"true && true: {condition1 && condition1}"); // true
// 逻辑或 (||)
Console.WriteLine($"true || false: {condition1 || condition2}"); // true
Console.WriteLine($"false || false: {condition2 || condition2}"); // false
// 逻辑非 (!)
Console.WriteLine($"!true: {!condition1}"); // false
Console.WriteLine($"!false: {!condition2}"); // true
// 组合使用
int age = 25;
bool isStudent = true;
bool canVote = (age >= 18) && isStudent; // 年龄大于等于18 且 是学生
Console.WriteLine($"Can vote? {canVote}"); // true
bool hasPermission = (age < 18) || (age >= 60); // 年龄小于18 或 年龄大于等于60
Console.WriteLine($"Has special permission? {hasPermission}"); // false
}
}
}
位运算符
对整数类型的二进制位进行操作。
&(按位与): 两个位都为 1 时,结果位为 1。|(按位或): 两个位有一个为 1 时,结果位为 1。^(按位异或): 两个位不同时,结果位为 1。~(按位取反): 翻转所有位。<<(左移): 将二进制位向左移动指定的位数,右侧空位补 0。>>(右移): 将二进制位向右移动指定的位数。对于有符号数,左侧空位通常补符号位(算术右移);对于无符号数,左侧空位补 0(逻辑右移)。
using System;
namespace BitwiseOperators
{
class Program
{
static void Main(string[] args)
{
int a = 5; // 二进制: 0101
int b = 3; // 二进制: 0011
// 按位与 (&)
Console.WriteLine($"a & b = {a & b}"); // 0001 (十进制: 1)
// 按位或 (|)
Console.WriteLine($"a | b = {a | b}"); // 0111 (十进制: 7)
// 按位异或 (^)
Console.WriteLine($"a ^ b = {a ^ b}"); // 0110 (十进制: 6)
// 按位取反 (~)
Console.WriteLine($"~a = {~a}"); // 取反结果取决于整数类型的大小和补码表示
// 左移 (<<)
Console.WriteLine($"a << 2 = {a << 2}"); // 010100 (十进制: 20)
// 右移 (>>)
Console.WriteLine($"a >> 1 = {a >> 1}"); // 0010 (十进制: 2)
}
}
}
三元运算符(条件运算符)
一种简洁的 if-else 语句的替代形式,用于根据条件返回两个值之一。
语法:条件 ? 值如果为真 : 值如果为假;
using System;
namespace TernaryOperator
{
class Program
{
static void Main(string[] args)
{
int score = 75;
string result = (score >= 60) ? "及格" : "不及格";
Console.WriteLine($"考试结果: {result}"); // 输出: 考试结果: 及格
int max = (10 > 5) ? 10 : 5;
Console.WriteLine($"两个数中的较大值: {max}"); // 输出: 两个数中的较大值: 10
}
}
}
控制流语句
条件分支语句 (if-else)
根据条件执行不同的代码块。
if (条件) { ... }: 如果条件为真,则执行if块中的代码。if (条件) { ... } else { ... }: 如果条件为真,执行if块;否则,执行else块。if (条件1) { ... } else if (条件2) { ... } else { ... }: 链式判断,按顺序检查条件,执行第一个为真的块;若所有条件都不满足,则执行最后的else块(如果存在)。
using System;
namespace IfElseStatements
{
class Program
{
static void Main(string[] args)
{
int temperature = 25;
if (temperature > 30)
{
Console.WriteLine("天气炎热!");
}
else if (temperature >= 20 && temperature <= 30)
{
Console.WriteLine("天气舒适。");
}
else if (temperature < 10)
{
Console.WriteLine("天气寒冷!");
}
else
{
Console.WriteLine("天气温和。");
}
}
}
}
switch 语句
一种多路分支结构,用于根据一个变量的多个可能值来执行不同的代码块。常用于处理枚举类型或常量值。
using System;
namespace SwitchStatement
{
class Program
{
static void Main(string[] args)
{
int dayOfWeek = 3; // 假设 1=周一, ..., 7=周日
switch (dayOfWeek)
{
case 1:
Console.WriteLine("星期一");
break;
case 2:
Console.WriteLine("星期二");
break;
case 3:
Console.WriteLine("星期三");
break;
case 4:
Console.WriteLine("星期四");
break;
case 5:
Console.WriteLine("星期五");
break;
case 6:
case 7: // 贯穿(fall-through): 6 和 7 都执行同一个逻辑
Console.WriteLine("周末");
break;
default: // 如果以上 case 都不匹配
Console.WriteLine("无效的日期");
break;
}
}
}
}
循环语句
while 循环
当指定条件为 true 时,重复执行代码块。适用于循环次数不确定的情况。
using System;
namespace WhileLoop
{
class Program
{
static void Main(string[] args)
{
int count = 0;
// 当 count 小于 5 时,循环继续
while (count < 5)
{
Console.WriteLine($"Count is: {count}");
count++; // 增加 count 的值,否则可能导致无限循环
}
Console.WriteLine("While loop finished.");
// 模拟一个需要持续检查条件的场景(如游戏主循环)
// while (true) { /* 处理游戏逻辑 */ }
}
}
}
for 循环
一种更紧凑的循环结构,通常用于循环次数已知或可以确定的情况。包含初始化、条件和迭代三个部分。
using System;
namespace ForLoop
{
class Program
{
static void Main(string[] args)
{
// 循环从 0 到 4
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}
// 循环从 5 到 1
for (int j = 5; j > 0; j--)
{
Console.WriteLine($"Countdown: {j}");
}
// 嵌套 for 循环 (例如打印九九乘法表)
for (int row = 1; row <= 9; row++)
{
for (int col = 1; col <= row; col++)
{
Console.Write($"{col}x{row}={col * row}\t");
}
Console.WriteLine(); // 每行结束后换行
}
}
}
}
控制台操作
Console 类提供了与控制台交互的功能。
Console.Write(text): 输出文本,不换行。Console.WriteLine(text): 输出文本,并换行。Console.ReadLine(): 读取用户输入的整行文本。Console.ReadKey(intercept: true): 读取用户按下的单个键,intercept: true表示不将按键显示在控制台上。Console.Clear(): 清空控制台屏幕。Console.SetWindowSize(width, height): 设置控制台窗口大小。Console.SetBufferSize(width, height): 设置控制台缓冲区大小。Console.SetCursorPosition(left, top): 设置光标的位置。Console.ForegroundColor,Console.BackgroundColor: 设置文本或背景颜色。Console.CursorVisible: 控制光标是否可见。
using System;
namespace ConsoleOperations
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始控制台操作演示...");
// 设置颜色
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("这是黄色的文本。");
Console.ResetColor(); // 重置为默认颜色
// 设置光标位置
Console.SetCursorPosition(10, 5);
Console.Write("在指定位置输出。");
Console.WriteLine(); // 换行
// 隐藏光标
Console.CursorVisible = false;
Console.WriteLine("光标已隐藏。");
// Console.CursorVisible = true; // 显示光标
// 清屏
// Console.ReadKey(); // 等待用户按键
// Console.Clear();
// Console.WriteLine("控制台已清屏。");
Console.WriteLine("控制台操作演示结束。");
}
}
}
随机数
使用 System.Random 类生成伪随机数。
new Random(): 创建一个随机数生成器实例。random.Next(): 生成一个非负随机整数。random.Next(maxValue): 生成一个介于 0(包含)和maxValue(不包含)之间的随机整数。random.Next(minValue, maxValue): 生成一个介于minValue(包含)和maxValue(不包含)之间的随机整数。
using System;
namespace RandomNumbers
{
class Program
{
static void Main(string[] args)
{
Random randomGenerator = new Random();
// 生成一个随机整数
int randomInt = randomGenerator.Next();
Console.WriteLine($"随机整数: {randomInt}");
// 生成一个 0 到 99 的随机整数
int randomUpTo100 = randomGenerator.Next(100);
Console.WriteLine($"0-99 之间的随机数: {randomUpTo100}");
// 生成一个 10 到 19 的随机整数
int randomInRange = randomGenerator.Next(10, 20);
Console.WriteLine($"10-19 之间的随机数: {randomInRange}");
}
}
}
简单项目示例:猜数字游戏
一个结合了变量、输入输出、循环、条件判断和随机数的简单控制台小游戏。
using System;
namespace GuessNumberGame
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("欢迎来到猜数字游戏!");
Console.WriteLine("请猜一个 1 到 100 之间的数字。");
Random random = new Random();
int secretNumber = random.Next(1, 101); // 生成 1 到 100 的秘密数字
int guessCount = 0;
int userGuess = 0;
while (userGuess != secretNumber)
{
Console.Write("请输入你的猜测: ");
string input = Console.ReadLine();
// 尝试将输入转换为整数,并处理可能的格式错误
if (!int.TryParse(input, out userGuess))
{
Console.WriteLine("输入无效,请输入一个整数。");
continue; // 跳过本次循环的剩余部分,重新开始
}
guessCount++; // 猜测次数加一
if (userGuess < secretNumber)
{
Console.WriteLine("太小了!请猜一个更大的数字。");
}
else if (userGuess > secretNumber)
{
Console.WriteLine("太大了!请猜一个更小的数字。");
}
else
{
Console.WriteLine($"恭喜你!你猜对了!秘密数字是 {secretNumber}。");
Console.WriteLine($"你一共猜了 {guessCount} 次。");
}
}
Console.WriteLine("游戏结束。按任意键退出。");
Console.ReadKey();
}
}
}