代码之家  ›  专栏  ›  技术社区  ›  Chris

VB.NET:优化多个类的初始化

  •  1
  • Chris  · 技术社区  · 17 年前

        addTemplateToList(New docNULL)
        addTemplateToList(New docAgenda)
        addTemplateToList(New docAgendaNew)
        addTemplateToList(New docOffer)
        :
          20 more
        :
        addTemplateToList(New docRequest)
    

    所有类都继承docMain,addTemplateToList(X)将X添加到(docMain的)列表中。

    我想到了这样的事情:

    for all x as docMain in ALLAVAILABLECLASSES
      if x.className().beginswith("doc") then addTemplateToList(x)
    next
    

    这在VB.net中是否可能(反射?)?

    3 回复  |  直到 17 年前
        1
  •  1
  •   Chris    17 年前

    我找到了一个非常简单的解决方案:

        Dim m As Type = Type.GetType("mainARGQ.docCreator")
        For Each TypeObj As Type In [Assembly].GetExecutingAssembly().GetTypes()
            If TypeObj.BaseType Is m And TypeObj IsNot m Then
                addTemplateToList(Activator.CreateInstance(TypeObj))
            End If
        Next
    

        2
  •  0
  •   Thirler    17 年前

    http://www.vbdotnetheaven.com/UploadFile/rahul4_saxena/Reflection09122007031247AM/Reflection.aspx

    请注意,尽管这会使您的代码更灵活/更短。这不是优化,反射通常是程序中昂贵的功能。

        3
  •  0
  •   dr. evil    17 年前

    你需要使用反射,最好使用MEF( http://www.codeplex.com/MEF

    正如有人之前所说的那样,它不会使速度更快,但会降低代码的灵活性。