Can I use Activator.CreateInstance with an Interface?

前端 未结 6 1462
故里飘歌
故里飘歌 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:47

    This is some code i have used a few times. It finds all types in an assembly that implement a certain interface:

    Type[] iLoadTypes = (from t in Assembly.Load("ClassLibrary1").GetExportedTypes()
                         where !t.IsInterface && !t.IsAbstract
                         where typeof(ILoad).IsAssignableFrom(t)
                         select t).ToArray();
    

    Then you have all types in ClassLibrary1 that implement ILoad.

    You could then instantiate all of them:

    ILoad[] instantiatedTypes = 
        iLoadTypes.Select(t => (ILoad)Activator.CreateInstance(t)).ToArray();
    

提交回复
热议问题