Can I use Activator.CreateInstance with an Interface?

前端 未结 6 1510
故里飘歌
故里飘歌 2021-01-04 00:21

I have an example:

        Assembly asm = Assembly.Load(\"ClassLibrary1\");
        Type ob = asm.GetType(\"ClassLibrary1.UserControl1\");
        UserContro         


        
6条回答
  •  情书的邮戳
    2021-01-04 00:46

    You cannot create instance of an interface, but if

    UserControl1 implements ILoad inteface

    you can use resulting object as ILoad

    ILoad uc = (ILoad)Activator.CreateInstance(ob);
    grd.Children.Add(uc);
    

    Moreover, you do not need to treat it via interface, if you write

    UserControl1 uc = (UserControl1)Activator.CreateInstance(ob);
    grd.Children.Add(uc);
    

    Members of ILoad would be callable as uc.SomeILoadMethod();

提交回复
热议问题