基本结构
using System; // 'using' allows for easier access to types in a namespace.
namespace YourNamespace // Namespaces organize code and prevent naming collisions.
{
class YourClass // A 'class' defines the blueprint of objects.
{
static void Main(string[] args) // 'Main' is where the program starts execution.
{
Console.WriteLine("Hello, World!"); // Displays text in the console.
}
}
}
数据类型
值类型和引用类型
变量
int x = 1;
常量
const int x = 1;
条件语句
- 有括号
- switch要break
循环语句
特别的
foreach (var item in itemList){
//...
}
array
固定大小
List
using System.Collections.Generic; // Required namespace for Lists.
List<int> list = new List<int>() {1, 2, 3, 4, 5}; // Initializes a List with 5 integers.
list.Add(6); // Add the number 6 to the list
list.Remove(2) // Remove the element at index 2 (0-based) from the list.
Dictionary
也在上面的Generic namespace下
方法
类&对象
exception handling
try catch finally
Delegates, Events & Lambdas
Delegates(委托)
参考:https://www.runoob.com/csharp/csharp-delegate.html
类似于对特定函数样式的引用,通常在event中用的较多。委托的概念使得lambda语句得以实现。
LINQ(待学习)
参考:https://www.cainiaojc.com/linq/why-linq.html
属性
另一种注释的方法,可以用来标注deprecated方法等
[Obsolete("This method is deprecated.")] // An attribute warning developers about deprecated methods.
public void OldMethod() { /*...*/ }
Async / Await
实验室项目无需使用,暂时不用学
杂项
- enum
enum Gender {
Male,
Female
}
void ShowGender(){
var myGender = Gender.Male;
Console.WriteLine(myGender);
}
- interface
接口可以定义派生类或派生接口的属性、方法和事件,用于继承。
interface IMyInterface { // ⭐接口名习惯以I开头
int LanguageCode;
void Greet(string name);
}
class MyGreeter: IMyInterface { // 用冒号表示继承
int LanguageCode = 26;
void Greet(string name) {
// ...
}
}
- class
- 隐式继承System.Object,存储在堆上
- record
就是class的简洁版,同时拥有三个特性:1. immutable 2. 解构 3. 可以使用with语句
record Dimension(int Width, int Height);
var d = new Dimension(12,24);
var (w, _) = d;
var d2 = d with {Height = 1000};
- struct
与class基本相同,只是struct是值类型,class是引用类型. class, struct, record可以放在一起记忆,参考https://www.cnblogs.com/keatkeat/p/16513491.html
- dynamic
- 将类型确定推迟到运行期间
- is, as
- 用于类型检查和类型转换
- var
- 语法糖,编译器会将类型对应好
- nameof
- 编译时转换为类、方法、变量名(不影响性能)
字符串操作
string.Concat(); // Combines multiple strings.
string.Join(); // Joins elements with a separator.
str.Split(); // Splits a string based on delimiters.
str.ToUpper(); // Converts to uppercase.
str.ToLower(); // Converts to lowercase.
str.Trim(); // Removes leading and trailing whitespace.
str.Substring(); // Extracts a portion of the string.
文件操作
using System.IO; // Necessary for most File I/O operations.
File.ReadAllText(path); // Reads the entire content of a file into a string.
File.WriteAllText(path, content); // Writes a string to a file, creating or overwriting it.
File.Exists(path); // Checks if a file exists at the specified path.
日期和时间
DateTime current = DateTime.Now; // Gets the current date and time.
current.AddDays(1); // Adds a day to the current date.
current.ToShortDateString(); // Converts the date to a short date string format.
Generics
class HollyCow<T> {
public static void Cow(T str){
Console.WriteLine(str);
}
}
Nullables
int? nullableInt = null; // '?' makes the int nullable.
bool hasValue = nullableInt.HasValue; // Checks if nullable type has a value.
Attributes & Reflections(待学习)
扩展方法
这个讲得比较清楚了:https://www.cainiaojc.com/csharp/csharp-extension-method.html
可以将扩展方法添加到您自己的自定义类,.NET Framework类或第三方类或接口中
依赖注入
依赖注入是控制反转的实现方式之一。
控制反转
解耦合的一种方式,将不必要的控制交给实际需要的地方决定。
依赖注入
在这个地方需要用另外一个地方的代码,那么就将另外一个地方的代码作为“依赖”“注入”到这里。
Partial Classes
partial关键词可以讲一个类的定义分割到不同的文件中。
public partial class MyClass{
// ...
}
public partial class MyClass{
// ...
}
Interoperability (互操作性)
C#支持使用win32 api函数
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr h, string m, string c, int type);
匿名结构体
var anon = new { Name = "John", Age = 25 };
元组(tuples)
元组的元素数量和顺序是明确的,但元素类型可以是任意的
var person = Tuple.Create("John", 25);
模式匹配(待学习)
局部函数
在方法中可以定义局部函数,而无需将其作为方法添加到某个类里面。
public void MyMethod(){
void LocalFunction(){
// ...
}
LocalFunction();
}
记录(records)
见杂项
with
见杂项
数组元素访问(待学习)
using和IDisposable接口
using可以控制一个变量的有效范围,在超出范围是,会调用该变量的Dispose方法
使用此二者的组合,可以实现golang中defer语句的效果