反射是.NET中的一个功能,它允许你在运行时动态获取程序集、类型、成员等的信息,并且可以执行操作,比如创建对象、调用方法、获取属性等。
下面是一个使用反射在.NET中创建对象的示例代码:
using System;
using System.Reflection;
namespace ReflectionDemo
{class Program
{
static void Main(string[] args)
{
// 获取程序集
Assembly assembly = Assembly.Load("MyAssembly");
// 获取类型
Type type = assembly.GetType("MyType");
// 创建对象
object obj = Activator.CreateInstance(type);
// 调用方法
MethodInfo method = type.GetMethod("MyMethod");
method.Invoke(obj, null);
// 获取属性
PropertyInfo property = type.GetProperty("MyProperty");
object value = property.GetValue(obj);
Console.WriteLine(value);
}
}
}
上面的代码中,我们首先使用Assembly.Load
方法获取程序集,然后使用GetType
方法获取类型,接着使用Activator.CreateInstance
方法创建对象,最后使用GetMethod
和Invoke
方法调用方法,使用GetProperty
和GetValue
方法获取属性的值。