C#反射:探索类的字段、属性与方法
在C#编程中,反射(Reflection) 是一种强大的机制,允许程序在运行时检查和操作自身的元数据(类型信息、成员信息等)。通过反射,我们可以:
- 动态获取类型(class/struct/interface等)的详细信息(字段、属性、方法、构造函数等)。
- 动态创建类型的实例(即使类型在编译时未知)。
- 动态调用方法、修改字段/属性值,甚至访问私有成员。
反射广泛应用于依赖注入、ORM框架(如Entity Framework)、插件系统、序列化/反序列化、单元测试等场景。本文将深入讲解如何使用C#反射机制,全面探索类的字段、属性和方法,并分享实践经验与最佳实践。
目录#
- C#反射基础
- 反射获取字段(Field)
- 2.1 字段的元数据:
FieldInfo - 2.2 获取公共/私有/静态字段
- 2.3 读取与修改字段值
- 2.1 字段的元数据:
- 反射获取属性(Property)
- 3.1 属性的元数据:
PropertyInfo - 3.2 获取公共/私有属性
- 3.3 读取与设置属性值
- 3.1 属性的元数据:
- 反射获取方法(Method)
- 4.1 方法的元数据:
MethodInfo - 4.2 获取公共/私有/静态方法
- 4.3 动态调用方法
- 4.1 方法的元数据:
- 常见实践与最佳实践
- 性能考量
- 总结
- 参考
C#反射基础#
反射的核心在于System.Reflection命名空间,其中最关键的类型是Type(表示类型的元数据)和一系列*Info类(如FieldInfo、PropertyInfo、MethodInfo),用于描述类型的成员。
获取Type的三种方式#
-
typeof关键字:编译时已知类型。Type typeOfString = typeof(string); -
object.GetType()方法:运行时从实例获取类型(实例必须非空)。string str = "Hello"; Type typeFromInstance = str.GetType(); -
Type.GetType(string)方法:通过类型的完全限定名(命名空间+类名)获取类型(需包含程序集信息,否则可能返回null)。Type typeOfList = Type.GetType("System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
反射获取字段(Field)#
字段是类/结构体中直接存储数据的成员(如private int age;)。反射可用于发现和操作这些字段。
2.1 字段的元数据:FieldInfo#
FieldInfo类封装了字段的元数据,包括:
- 名称(
Name)、类型(FieldType) - 访问修饰符(
IsPublic、IsPrivate、IsStatic等) - 操作方法(
GetValue()、SetValue())
2.2 获取公共/私有/静态字段#
使用Type.GetFields()或Type.GetField()方法,结合BindingFlags枚举指定搜索范围:
BindingFlags.Public:仅公共字段(默认)。BindingFlags.NonPublic:私有、受保护、内部字段。BindingFlags.Instance:实例字段。BindingFlags.Static:静态字段。BindingFlags.DeclaredOnly:仅当前类型声明的字段(不包含继承的)。
示例:定义一个类并反射其字段
using System;
using System.Reflection;
public class Person
{
// 公共实例字段
public string Name;
// 私有实例字段
private int _age;
// 公共静态字段
public static string Country = "China";
// 私有静态字段
private static int _population = 1400000000;
}
class Program
{
static void Main()
{
Type personType = typeof(Person);
// 1. 获取所有公共字段(包括继承的,但Person无父类)
FieldInfo[] publicFields = personType.GetFields();
Console.WriteLine("公共字段:");
foreach (var field in publicFields)
{
Console.WriteLine($" {field.Name} (类型: {field.FieldType})");
}
// 2. 获取指定名称的公共字段
FieldInfo nameField = personType.GetField("Name");
Console.WriteLine($"找到字段 Name: {nameField.FieldType}");
// 3. 获取私有实例字段(需指定BindingFlags)
FieldInfo ageField = personType.GetField("_age",
BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine($"找到私有字段 _age: {ageField.FieldType}");
// 4. 获取静态字段(需指定BindingFlags)
FieldInfo countryField = personType.GetField("Country",
BindingFlags.Public | BindingFlags.Static);
FieldInfo populationField = personType.GetField("_population",
BindingFlags.NonPublic | BindingFlags.Static);
Console.WriteLine($"找到静态字段 Country: {countryField.FieldType}");
Console.WriteLine($"找到私有静态字段 _population: {populationField.FieldType}");
}
}2.3 读取与修改字段值#
通过FieldInfo.GetValue()(读取)和FieldInfo.SetValue()(修改)操作字段,注意:
- 对于实例字段,需传入类的实例;对于静态字段,实例参数传
null。 - 若字段为私有,需先设置
fieldInfo.IsAccessible = true;(.NET Core 2.1+)或fieldInfo.SetAccessible(true);(旧版本,需using System.Reflection;)。
示例:修改Person的字段值
// 创建Person实例
Person person = new Person { Name = "Alice" };
Type personType = typeof(Person);
// 读取公共实例字段Name
FieldInfo nameField = personType.GetField("Name");
string name = (string)nameField.GetValue(person);
Console.WriteLine($"原始Name: {name}");
// 修改公共实例字段Name
nameField.SetValue(person, "Bob");
Console.WriteLine($"修改后Name: {person.Name}");
// 读取私有实例字段_age(需设置可访问)
FieldInfo ageField = personType.GetField("_age",
BindingFlags.NonPublic | BindingFlags.Instance);
ageField.IsAccessible = true; // .NET Core 2.1+
int age = (int)ageField.GetValue(person); // 初始为0
Console.WriteLine($"原始_age: {age}");
// 修改私有实例字段_age
ageField.SetValue(person, 30);
int newAge = (int)ageField.GetValue(person);
Console.WriteLine($"修改后_age: {newAge}");
// 读取/修改静态字段
FieldInfo countryField = personType.GetField("Country",
BindingFlags.Public | BindingFlags.Static);
string country = (string)countryField.GetValue(null); // 静态字段传null
Console.WriteLine($"原始Country: {country}");
countryField.SetValue(null, "USA");
Console.WriteLine($"修改后Country: {Person.Country}");
// 读取/修改私有静态字段
FieldInfo populationField = personType.GetField("_population",
BindingFlags.NonPublic | BindingFlags.Static);
populationField.IsAccessible = true;
int population = (int)populationField.GetValue(null);
Console.WriteLine($"原始_population: {population}");
populationField.SetValue(null, 1500000000);
int newPopulation = (int)populationField.GetValue(null);
Console.WriteLine($"修改后_population: {newPopulation}");反射获取属性(Property)#
属性是对字段的封装(如public int Age { get; set; }),反射可操作其get/set方法。
3.1 属性的元数据:PropertyInfo#
PropertyInfo类封装了属性的元数据,包括:
- 名称(
Name)、类型(PropertyType) - 访问修饰符(
CanRead、CanWrite、GetMethod/SetMethod的可见性) - 操作方法(
GetValue()、SetValue())
3.2 获取公共/私有属性#
使用Type.GetProperties()或Type.GetProperty(),结合BindingFlags:
示例:定义带属性的类并反射
public class Product
{
// 公共属性(自动实现)
public string Name { get; set; }
// 私有setter的公共属性
public decimal Price { get; private set; }
// 私有属性
private int _stock { get; set; }
// 公共静态属性
public static string Category { get; set; } = "Electronics";
}
class Program
{
static void Main()
{
Type productType = typeof(Product);
// 1. 获取所有公共属性(包括继承的,Product无父类)
PropertyInfo[] publicProps = productType.GetProperties();
Console.WriteLine("公共属性:");
foreach (var prop in publicProps)
{
Console.WriteLine($" {prop.Name} (类型: {prop.PropertyType}, 可读: {prop.CanRead}, 可写: {prop.CanWrite})");
}
// 2. 获取指定名称的公共属性
PropertyInfo nameProp = productType.GetProperty("Name");
Console.WriteLine($"找到属性 Name: {nameProp.PropertyType}");
// 3. 获取私有setter的属性(Price的SetMethod是私有的)
PropertyInfo priceProp = productType.GetProperty("Price");
Console.WriteLine($"Price的SetMethod可见性: {priceProp.SetMethod.IsPublic}"); // 输出False
// 4. 获取私有属性(需指定BindingFlags)
PropertyInfo stockProp = productType.GetProperty("_stock",
BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine($"找到私有属性 _stock: {stockProp.PropertyType}");
// 5. 获取静态属性
PropertyInfo categoryProp = productType.GetProperty("Category",
BindingFlags.Public | BindingFlags.Static);
Console.WriteLine($"找到静态属性 Category: {categoryProp.PropertyType}");
}
}3.3 读取与设置属性值#
通过PropertyInfo.GetValue()和PropertyInfo.SetValue()操作属性,注意:
- 若属性的
set方法是私有,需设置propertyInfo.SetMethod.IsAccessible = true;(.NET Core 2.1+)或propertyInfo.SetMethod.SetAccessible(true);(旧版本)。
示例:操作Product的属性
// 创建Product实例
Product product = new Product { Name = "Laptop", Price = 999.99m };
Type productType = typeof(Product);
// 1. 读取/修改公共属性(Name)
PropertyInfo nameProp = productType.GetProperty("Name");
string originalName = (string)nameProp.GetValue(product);
Console.WriteLine($"原始Name: {originalName}");
nameProp.SetValue(product, "Desktop");
Console.WriteLine($"修改后Name: {product.Name}");
// 2. 读取/修改私有setter的属性(Price)
PropertyInfo priceProp = productType.GetProperty("Price");
decimal originalPrice = (decimal)priceProp.GetValue(product);
Console.WriteLine($"原始Price: {originalPrice}");
// 修改Price(SetMethod是私有的,需设置可访问)
priceProp.SetMethod.IsAccessible = true; // .NET Core 2.1+
priceProp.SetValue(product, 1299.99m);
decimal newPrice = (decimal)priceProp.GetValue(product);
Console.WriteLine($"修改后Price: {newPrice}");
// 3. 读取/修改私有属性(_stock)
PropertyInfo stockProp = productType.GetProperty("_stock",
BindingFlags.NonPublic | BindingFlags.Instance);
stockProp.SetMethod.IsAccessible = true; // 允许设置私有setter
stockProp.GetMethod.IsAccessible = true; // 允许读取私有getter
stockProp.SetValue(product, 100);
int stock = (int)stockProp.GetValue(product);
Console.WriteLine($"Stock: {stock}");
// 4. 读取/修改静态属性(Category)
PropertyInfo categoryProp = productType.GetProperty("Category",
BindingFlags.Public | BindingFlags.Static);
string originalCategory = (string)categoryProp.GetValue(null); // 静态属性传null
Console.WriteLine($"原始Category: {originalCategory}");
categoryProp.SetValue(null, "Books");
Console.WriteLine($"修改后Category: {Product.Category}");反射获取方法(Method)#
方法是类中包含逻辑的成员(如public void SayHello()、private int Add(int a, int b)),反射可动态调用它们。
4.1 方法的元数据:MethodInfo#
MethodInfo类封装了方法的元数据,包括:
- 名称(
Name)、返回类型(ReturnType)、参数(GetParameters()) - 访问修饰符(
IsPublic、IsPrivate、IsStatic等) - 调用方法(
Invoke())
4.2 获取公共/私有/静态方法#
使用Type.GetMethods()或Type.GetMethod(),结合BindingFlags:
示例:定义带方法的类并反射
public class Calculator
{
// 公共无参方法
public void SayHello() => Console.WriteLine("Hello!");
// 公共带参方法
public int Add(int a, int b) => a + b;
// 私有方法
private string FormatResult(int result) => $"Result: {result}";
// 公共静态方法
public static int Multiply(int a, int b) => a * b;
}
class Program
{
static void Main()
{
Type calcType = typeof(Calculator);
// 1. 获取所有公共方法(包括继承的,Calculator继承自object,所以包含ToString等)
MethodInfo[] publicMethods = calcType.GetMethods();
Console.WriteLine("公共方法:");
foreach (var method in publicMethods)
{
Console.WriteLine($" {method.Name} (返回类型: {method.ReturnType}, 参数数: {method.GetParameters().Length})");
}
// 2. 获取指定名称的公共方法(Add)
MethodInfo addMethod = calcType.GetMethod("Add",
new[] { typeof(int), typeof(int) }); // 指定参数类型
Console.WriteLine($"找到方法 Add: 返回类型 {addMethod.ReturnType}, 参数: {string.Join(", ", addMethod.GetParameters().Select(p => p.ParameterType))}");
// 3. 获取私有方法(需指定BindingFlags)
MethodInfo formatMethod = calcType.GetMethod("FormatResult",
BindingFlags.NonPublic | BindingFlags.Instance,
binder: null,
types: new[] { typeof(int) },
modifiers: null);
Console.WriteLine($"找到私有方法 FormatResult: {formatMethod.ReturnType}");
// 4. 获取静态方法
MethodInfo multiplyMethod = calcType.GetMethod("Multiply",
BindingFlags.Public | BindingFlags.Static,
binder: null,
types: new[] { typeof(int), typeof(int) },
modifiers: null);
Console.WriteLine($"找到静态方法 Multiply: {multiplyMethod.ReturnType}");
}
}4.3 动态调用方法#
通过MethodInfo.Invoke()调用方法,参数:
- 实例方法:传入类的实例;静态方法:传入
null。 - 参数数组:按方法参数顺序传递(无参则传
null或空数组)。
示例:调用Calculator的方法
// 创建Calculator实例
Calculator calc = new Calculator();
Type calcType = typeof(Calculator);
// 1. 调用公共无参方法(SayHello)
MethodInfo sayHelloMethod = calcType.GetMethod("SayHello");
sayHelloMethod.Invoke(calc, null); // 输出Hello!
// 2. 调用公共带参方法(Add)
MethodInfo addMethod = calcType.GetMethod("Add", new[] { typeof(int), typeof(int) });
object addResult = addMethod.Invoke(calc, new object[] { 5, 3 });
Console.WriteLine($"Add结果: {addResult}"); // 输出8
// 3. 调用私有方法(FormatResult,需设置可访问)
MethodInfo formatMethod = calcType.GetMethod("FormatResult",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] { typeof(int) },
null);
formatMethod.IsAccessible = true; // .NET Core 2.1+
object formatResult = formatMethod.Invoke(calc, new object[] { 10 });
Console.WriteLine($"FormatResult: {formatResult}"); // 输出Result: 10
// 4. 调用静态方法(Multiply)
MethodInfo multiplyMethod = calcType.GetMethod("Multiply",
BindingFlags.Public | BindingFlags.Static,
null,
new[] { typeof(int), typeof(int) },
null);
object multiplyResult = multiplyMethod.Invoke(null, new object[] { 4, 6 });
Console.WriteLine($"Multiply结果: {multiplyResult}"); // 输出24常见实践与最佳实践#
常见实践#
- ORM框架映射:将类的字段/属性映射到数据库表的列(如Entity Framework通过反射发现实体的属性)。
- 依赖注入(DI):动态创建服务实例,调用构造函数或方法注入依赖。
- 插件系统:加载外部程序集(
.dll),反射找到实现特定接口的类并实例化。 - 序列化/反序列化:获取对象的字段/属性,转换为JSON、XML等格式(如Newtonsoft.Json通过反射序列化对象)。
最佳实践#
-
缓存元数据:反射操作(如
GetType()、GetField())开销较大,重复操作时应缓存Type、FieldInfo、PropertyInfo、MethodInfo。例如:private static readonly Dictionary<Type, PropertyInfo[]> _propertyCache = new(); public static PropertyInfo[] GetCachedProperties(Type type) { if (!_propertyCache.TryGetValue(type, out var props)) { props = type.GetProperties(); _propertyCache[type] = props; } return props; } -
精确使用BindingFlags:避免使用
BindingFlags.Default或过宽的标志,减少搜索范围(如仅需实例字段则用BindingFlags.Instance)。 -
处理访问修饰符:操作私有成员时,使用
IsAccessible = true(.NET Core)或SetAccessible(true)(旧版本),但避免滥用(破坏封装性)。 -
异常处理:反射操作可能抛出
TargetException(实例不匹配)、TargetInvocationException(方法执行时异常)、AmbiguousMatchException(多个匹配方法)等,需捕获并处理。
性能考量#
反射的性能开销主要来自:
- 元数据搜索(如
GetField()、GetMethod())。 - 动态调用的装箱/拆箱(值类型参数需装箱)。
优化方式:
- 缓存元数据:如前所述,缓存
Type、MemberInfo等。 - 使用Expression Tree或IL生成:对于高频调用,可通过
System.Linq.Expressions或System.Reflection.Emit生成动态方法,性能接近直接调用。 - 避免不必要的反射:仅在动态性需求(如插件、序列化)时使用,静态场景优先直接调用。
总结#
C#反射是运行时操作类型的强大工具,通过System.Reflection命名空间,我们可以:
- 字段:发现并修改公共/私有/静态字段。
- 属性:操作带
get/set的属性(包括私有访问器)。 - 方法:动态调用无参/带参、实例/静态、公共/私有方法。
在实践中,需结合缓存、精确的BindingFlags和异常处理,并在性能敏感场景考虑优化(如Expression Tree)。反射虽强大,但应谨慎使用,避免破坏封装性或造成性能瓶颈。
参考#
- Microsoft Docs - Reflection:https://learn.microsoft.com/zh-cn/dotnet/api/system.reflection
- 《CLR via C#》(Jeffrey Richter):深入讲解.NET类型系统与反射机制。
- dotnetperls - C# Reflection Tutorial:https://www.dotnetperls.com/reflection
- 最佳实践:https://docs.microsoft.com/zh-cn/dotnet/standard/assembly/reflect-assembly?redirectedfrom=MSDN