在C#中,可以使用反射來(lái)動(dòng)態(tài)地創(chuàng)建對(duì)象。下面是一些示例代碼,展示了如何使用反射來(lái)創(chuàng)建對(duì)象:
Type type = typeof(MyClass); // 要?jiǎng)?chuàng)建對(duì)象的類(lèi)型
object obj = Activator.CreateInstance(type); // 創(chuàng)建對(duì)象
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ì)象
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ì)象。