我有使用Activator.CreateInstance動態創建實例。但是,它表示在每次嘗試時對象都不能爲空。粘貼下面的代碼。我做錯了什麼?Activator.CreateInstance失敗
有如果
Activator.CreateInstance
代替用於確定在運行時間的對象類型的現有開關/ case語句的任何問題?謝謝。
public abstract class Base
{
public abstract void Func();
}
public class Derived:Base
{
public override void Func()
{
MessageBox.Show("Derived First");
}
}
public class Derived2 : Base
{
public override void Func()
{
MessageBox.Show("Derived Second");
}
}
private void button1_Click(object sender, EventArgs e)
{
// I was trying to make use of the overladed version
// where it takes the Type as parameter.
BaseClass report =
(BaseClass) Activator.CreateInstance(Type.GetType("Derived"));
report.Func();
}
你爲什麼不使用typeof運算(),而不是Type.GetType()? –