跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
C Sharp 语法
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= C#语法 = C#语法是C#编程语言的基础结构,它定义了如何编写有效的C#代码。C#是一种强类型、面向对象的语言,其语法类似于其他C风格语言(如C++和Java),但具有独特的特性和简化。理解C#语法是掌握该语言的第一步。 == 基本语法结构 == C#程序由以下基本元素组成: * '''命名空间(Namespace)''':用于组织代码 * '''类(Class)''':定义对象的结构和行为 * '''方法(Method)''':包含可执行代码 * '''语句(Statement)''':执行操作的指令 * '''表达式(Expression)''':产生值的代码片段 * '''注释(Comments)''':解释代码的非执行文本 以下是一个简单的C#程序示例: <syntaxhighlight lang="csharp"> using System; namespace HelloWorld { class Program { static void Main(string[] args) { // 这是一个简单的C#程序 Console.WriteLine("Hello, World!"); } } } </syntaxhighlight> 输出: <pre> Hello, World! </pre> == 变量和数据类型 == C#是强类型语言,所有变量都必须先声明后使用。C#支持多种数据类型: === 值类型 === * 整数类型:<code>int</code>, <code>long</code>, <code>short</code>, <code>byte</code> * 浮点类型:<code>float</code>, <code>double</code>, <code>decimal</code> * 布尔类型:<code>bool</code> * 字符类型:<code>char</code> === 引用类型 === * 字符串:<code>string</code> * 对象:<code>object</code> * 动态类型:<code>dynamic</code> 变量声明示例: <syntaxhighlight lang="csharp"> int age = 25; // 整数 double price = 19.99; // 双精度浮点数 char grade = 'A'; // 字符 string name = "John Doe"; // 字符串 bool isActive = true; // 布尔值 </syntaxhighlight> == 运算符 == C#提供多种运算符: === 算术运算符 === <math>+</math>, <math>-</math>, <math>*</math>, <math>/</math>, <math>\%</math> (取模) === 关系运算符 === <math>==</math>, <math>!=</math>, <math>></math>, <math><</math>, <math>>=</math>, <math><=</math> === 逻辑运算符 === <math>\&\&</math> (AND), <math>||</math> (OR), <math>!</math> (NOT) === 赋值运算符 === <math>=</math>, <math>+=</math>, <math>-=</math>, etc. 运算符示例: <syntaxhighlight lang="csharp"> int a = 10, b = 20; int sum = a + b; // 30 bool result = (a < b); // true </syntaxhighlight> == 控制结构 == C#提供多种控制程序流程的结构: === 条件语句 === <syntaxhighlight lang="csharp"> if (condition) { // 条件为真时执行 } else if (anotherCondition) { // 另一个条件为真时执行 } else { // 其他情况执行 } </syntaxhighlight> === 循环结构 === <syntaxhighlight lang="csharp"> // for循环 for (int i = 0; i < 10; i++) { Console.WriteLine(i); } // while循环 while (condition) { // 循环体 } // do-while循环 do { // 至少执行一次 } while (condition); </syntaxhighlight> === switch语句 === <syntaxhighlight lang="csharp"> switch (expression) { case value1: // 代码块 break; case value2: // 代码块 break; default: // 默认代码块 break; } </syntaxhighlight> == 方法 == 方法是包含一系列语句的代码块,可以接受参数并返回值。 方法定义语法: <syntaxhighlight lang="csharp"> [access-modifier] [return-type] [method-name]([parameters]) { // 方法体 return [value]; // 如果返回类型不是void } </syntaxhighlight> 示例: <syntaxhighlight lang="csharp"> public int Add(int a, int b) { return a + b; } // 调用方法 int result = Add(5, 3); // 返回8 </syntaxhighlight> == 类和对象 == C#是面向对象的语言,类是其基本构建块。 类定义示例: <syntaxhighlight lang="csharp"> public class Person { // 字段 public string Name; public int Age; // 方法 public void Introduce() { Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old."); } } // 使用类 Person person = new Person(); person.Name = "Alice"; person.Age = 30; person.Introduce(); </syntaxhighlight> 输出: <pre> Hi, I'm Alice and I'm 30 years old. </pre> == 异常处理 == C#使用try-catch块处理异常: <syntaxhighlight lang="csharp"> try { // 可能抛出异常的代码 int result = 10 / int.Parse("0"); } catch (DivideByZeroException ex) { Console.WriteLine("Cannot divide by zero!"); } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } finally { // 无论是否发生异常都会执行的代码 Console.WriteLine("Cleanup code here"); } </syntaxhighlight> == 实际应用案例 == 以下是一个简单的银行账户管理系统示例,展示了C#语法的实际应用: <syntaxhighlight lang="csharp"> public class BankAccount { private string _accountNumber; private decimal _balance; public BankAccount(string accountNumber, decimal initialBalance) { _accountNumber = accountNumber; _balance = initialBalance; } public void Deposit(decimal amount) { if (amount <= 0) throw new ArgumentException("Deposit amount must be positive"); _balance += amount; } public void Withdraw(decimal amount) { if (amount <= 0) throw new ArgumentException("Withdrawal amount must be positive"); if (amount > _balance) throw new InvalidOperationException("Insufficient funds"); _balance -= amount; } public decimal GetBalance() { return _balance; } } // 使用示例 BankAccount account = new BankAccount("123456789", 1000.00m); account.Deposit(500.00m); account.Withdraw(200.00m); Console.WriteLine($"Current balance: {account.GetBalance():C}"); </syntaxhighlight> 输出: <pre> Current balance: $1,300.00 </pre> == 高级语法特性 == 对于更高级的用户,C#还提供以下语法特性: === Lambda表达式 === <syntaxhighlight lang="csharp"> Func<int, int, int> add = (x, y) => x + y; int result = add(3, 4); // 7 </syntaxhighlight> === LINQ查询 === <syntaxhighlight lang="csharp"> var numbers = new List<int> { 1, 2, 3, 4, 5 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; </syntaxhighlight> === 异步编程 === <syntaxhighlight lang="csharp"> public async Task<string> FetchDataAsync() { HttpClient client = new HttpClient(); string result = await client.GetStringAsync("https://example.com"); return result; } </syntaxhighlight> == 语法关系图 == 以下mermaid图展示了C#基本语法元素之间的关系: <mermaid> graph TD A[C#程序] --> B[命名空间] A --> C[类] A --> D[接口] B --> E[类型声明] C --> F[字段] C --> G[属性] C --> H[方法] H --> I[语句] I --> J[表达式] I --> K[控制结构] </mermaid> == 总结 == C#语法提供了强大而灵活的方式来构建各种应用程序。从基本的数据类型和控制结构到高级的面向对象特性和现代语言功能,C#语法设计既考虑了初学者也考虑了经验丰富的开发人员的需求。通过掌握这些语法基础,开发者可以构建从简单控制台应用到复杂企业系统的各种解决方案。 [[Category:编程语言]] [[Category:C Sharp]] [[Category:C Sharp 基础]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)