第十章:高级主题
10.1 反射与元数据
反射是 .NET 框架中的一个强大功能,允许程序在运行时检查类型信息并动态调用方法。
示例代码:
csharp
复制
using System;
using System.Reflection;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
}
}
class Program
{
static void Main(string[] args)
{
Type personType = typeof(Person);
object person = Activator.CreateInstance(personType);
PropertyInfo nameProperty = personType.GetProperty("Name");
nameProperty.SetValue(person, "John");
PropertyInfo ageProperty = personType.GetProperty("Age");
ageProperty.SetValue(person, 25);
MethodInfo introduceMethod = personType.GetMethod("Introduce");
introduceMethod.Invoke(person, null);
}
}
10.2 特性(Attributes)
特性是用于向代码元素添加元数据的声明性标签。C# 提供了多种内置特性,如 [Serializable]、[Obsolete] 等。
示例代码:
csharp
复制
using System;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
[Obsolete("Use IntroduceV2 instead.")]
public void Introduce()
{
Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
}
public void IntroduceV2()
{
Console.WriteLine("Hi, I'm " + Name + " and I'm " + Age + " years old.");
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person { Name = "John", Age = 25 };
person.Introduce(); // 警告:方法已过时
person.IntroduceV2();
}
}
10.3 动态类型与动态编程
C# 提供了 dynamic 关键字,允许在编译时跳过类型检查,并在运行时解析类型。
示例代码:
csharp
复制
using System;
class Program
{
static void Main(string[] args)
{
dynamic obj = "Hello, World!";
Console.WriteLine(obj.Length); // 输出 13
obj = 10;
Console.WriteLine(obj + 5); // 输出 15
}
}
10.4 内存管理与垃圾回收
C# 使用垃圾回收器 (GC) 自动管理内存。开发者可以通过 IDisposable 接口和 using 语句来显式释放资源。
示例代码:
csharp
复制
using System;
class Resource : IDisposable
{
public Resource()
{
Console.WriteLine("Resource acquired.");
}
public void Dispose()
{
Console.WriteLine("Resource released.");
}
}
class Program
{
static void Main(string[] args)
{
using (Resource resource = new Resource())
{
Console.WriteLine("Using resource.");
}
}
}
课后练习题
- 简答题:
- 什么是反射?它的主要用途是什么?
- 特性的作用是什么?如何在 C# 中使用特性?
- dynamic 关键字的作用是什么?它与 var 关键字有什么区别?
- 编程题:
- 编写一个程序,使用反射动态调用一个类的方法。
- 创建一个自定义特性 [Author],并将其应用于类和方法。
- 编写一个程序,使用 IDisposable 接口管理资源。
下一篇:AOP实现原理浅析