Tôi đang tạo một Instance động bằng Activator.CreateInstance. Tuy nhiên, nó đang nói đối tượng không thể được null trên mọi nỗ lực. Dán mã bên dưới. Tôi có làm gì sai không?Activator.CreateInstance không
Có bất kỳ vấn đề nếu
Activator.CreateInstance
thay thế công tắc/trường hợp báo cáo thông thường để xác định loại đối tượng trong thời gian chạy? Cảm ơn.
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();
}
tại sao bạn không sử dụng typeof() thay vì Type.GetType() ?? –