C# 高级教程学习笔记
1. C# 引用类型和值类型
1.1 C# 值类型
C# 值类型包括整型、浮点型、布尔型、结构体等。在内存中,它们的值被直接存储。
csharpCopy Codeint a = 10;
float b = 3.14f;
bool c = true;
struct Point {
public int x;
public int y;
}
Point d = new Point { x = 1, y = 2 };
1.2 C# 引用类型
C# 引用类型包括类、数组、字符串、委托等。在内存中,它们的值是指向对象的引用。
csharpCopy Codeclass Person {
public string Name { get; set; }
public int Age { get; set; }
}
Person p = new Person { Name = "Tom", Age = 18 };
int[] arr = new int[] { 1, 2, 3 };
string str = "Hello World";
1.3 区别与联系
C# 值类型存储在栈上,引用类型存储在堆上。值类型的复制是按值传递,而引用类型的复制是按引用传递。
csharpCopy Codeint a = 10;
int b = a; // b 是 a 的一份拷贝
Person p1 = new Person { Name = "Tom", Age = 18 };
Person p2 = p1; // p2 和 p1 指向同一个对象
2. C# 索引器
C# 索引器允许对象像数组一样通过索引访问元素。
csharpCopy Codeclass MyArray {
private int[] data = new int[10];
public int this[int index] {
get { return data[index]; }
set { data[index] = value; }
}
}
MyArray arr = new MyArray();
arr[0] = 1;
int a = arr[0];
3. C# 扩展方法
C# 扩展方法允许为已有类型添加新的方法,而不必修改原始代码。
csharpCopy Codestatic class StringExtension {
public static string Reverse(this string str) {
char[] chars = str.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}
string str = "Hello World";
string reversedStr = str.Reverse(); // "dlroW olleH"
4. C# 异步和await关键字
C# 的 async 和 await 关键字可以简化异步编程模型。
csharpCopy Codeasync Task<int> FooAsync() {
int result = await GetDataAsync();
// 操作数据
return result;
}
5. C# LINQ查询
C# LINQ(Language Integrated Query)查询是一种简便的方式,用于在集合上执行各种操作,如过滤、排序、投影等。
csharpCopy Codeint[] arr = new int[] { 1, 2, 3 };
var query = from item in arr
where item > 1
select item * 2;
foreach (int i in query) {
Console.WriteLine(i);
}
以上是C# 高级教程的一些知识点和实例,希望对你有所帮助。