C# 反射(Reflection)的使用例子说明
首先,我们来看一个简单的例子:动态创建对象。假设我们有一个类Person,它有两个属性:姓名和年龄。我们可以使用反射来动态地创建Person类的实例,并给属性赋值。
```csharp
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
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);
Console.WriteLine($"Name: {nameProperty.GetValue(person)}, Age: {ageProperty.GetValue(person)}");
}
}
```
在上述代码中,我们首先使用typeof关键字获取Person类的Type对象。然后,使用Activator.CreateInstance方法动态地创建Person类的实例。接下来,我们使用GetProperty方法获取Name和Age属性的PropertyInfo对象,并使用SetValue方法给属性赋值。最后,我们使用GetValue方法获取属性的值,并输出到控制台。
这个例子展示了反射的动态创建对象的能力。在运行时,我们可以根据需要创建任意类型的对象,并对其属性进行赋值和访问。
接下来,我们来看一个更复杂的例子:动态调用方法。假设我们有一个类Calculator,它有两个方法:Add和Multiply。我们可以使用反射来动态地调用这些方法。
```csharp
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Multiply(int a, int b)
{
return a * b;
}
}
class Program
{
static void Main()
{
Type calculatorType = typeof(Calculator);
object calculator = Activator.CreateInstance(calculatorType);
MethodInfo addMethod = calculatorType.GetMethod("Add");
int result = (int)addMethod.Invoke(calculator, new object[] { 2, 3 });
Console.WriteLine($"Result: {result}");
}
}
```
在上述代码中,我们首先使用typeof关键字获取Calculator类的Type对象。然后,使用Activator.CreateInstance方法动态地创建Calculator类的实例。接下来,我们使用GetMethod方法获取Add方法的MethodInfo对象,并使用Invoke方法调用该方法。最后,我们将方法的返回值输出到控制台。
这个例子展示了反射的动态调用方法的能力。在运行时,我们可以根据需要调用任意类型的方法,并获取其返回值。
除了动态创建对象和调用方法,反射还可以用于访问和修改类型的成员,如字段、事件和构造函数等。下面是一个例子:动态访问字段。
```csharp
class Person
{
public string Name;
public int Age;
}
class Program
{
static void Main()
{
Type personType = typeof(Person);
object person = Activator.CreateInstance(personType);
FieldInfo nameField = personType.GetField("Name");
nameField.SetValue(person, "John");
FieldInfo ageField = personType.GetField("Age");
ageField.SetValue(person, 25);
Console.WriteLine($"Name: {nameField.GetValue(person)}, Age: {ageField.GetValue(person)}");
}
}
```
在上述代码中,我们首先使用typeof关键字获取Person类的Type对象。然后,使用Activator.CreateInstance方法动态地创建Person类的实例。接下来,我们使用GetField方法获取Name和Age字段的FieldInfo对象,并使用SetValue方法给字段赋值。最后,我们使用GetValue方法获取字段的值,并输出到控制台。
这个例子展示了反射的动态访问字段的能
免责声明:本文由用户上传,此文本数据来源于原作者,如有侵权请联系删除!转载此文是出于传递更多信息之目的。若有来源标注错误或侵犯了您的合法权益,请作者持权属证明与本网联系,我们将及时更正、删除,谢谢。