在C#中,CreateInstance
方法屬于System.Reflection
命名空間下的Type
類。它用于通過反射動態創建一個類的實例。CreateInstance
方法可以接受以下參數:
false
。private
、protected
等)。默認值為false
。示例:
using System;
using System.Reflection;
namespace ReflectionExample
{
class Program
{
static void Main(string[] args)
{
// 獲取要創建的類的類型信息
Type type = Type.GetType("ReflectionExample.MyClass");
// 使用CreateInstance方法創建類的實例
object instance = type.CreateInstance();
// 調用實例的方法
MethodInfo method = type.GetMethod("MyMethod");
method.Invoke(instance, new object[] { });
}
}
class MyClass
{
public void MyMethod()
{
Console.WriteLine("Hello, World!");
}
}
}
在這個例子中,我們使用CreateInstance
方法創建了一個MyClass
的實例,并調用了其MyMethod
方法。請注意,為了使這個例子正常工作,您需要將ReflectionExample
程序集添加到您的項目中。