C#怎么通過(guò)反射創(chuàng)建對(duì)象

c#
小億
249
2023-12-12 04:41:31

在C#中,可以使用反射來(lái)動(dòng)態(tài)地創(chuàng)建對(duì)象。下面是一些示例代碼,展示了如何使用反射來(lái)創(chuàng)建對(duì)象:

  1. 使用Activator.CreateInstance方法:
Type type = typeof(MyClass); // 要?jiǎng)?chuàng)建對(duì)象的類(lèi)型
object obj = Activator.CreateInstance(type); // 創(chuàng)建對(duì)象
  1. 使用Type的GetConstructor方法和ConstructorInfo的Invoke方法:
Type type = typeof(MyClass); // 要?jiǎng)?chuàng)建對(duì)象的類(lèi)型
ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); // 獲取無(wú)參數(shù)的構(gòu)造函數(shù)
object obj = constructor.Invoke(null); // 創(chuàng)建對(duì)象
  1. 使用Type的InvokeMember方法:
Type type = typeof(MyClass); // 要?jiǎng)?chuàng)建對(duì)象的類(lèi)型
object obj = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null); // 創(chuàng)建對(duì)象

在上述示例中,MyClass是要?jiǎng)?chuàng)建的對(duì)象的類(lèi)型??梢蕴鎿Q為實(shí)際的類(lèi)型,并根據(jù)需要選擇適合的方法來(lái)創(chuàng)建對(duì)象。

0