【问题标题】:C# Get a List of Classes in a Namespace per Reflection [duplicate]C#根据反射获取命名空间中的类列表[重复]
【发布时间】:2017-07-13 14:40:41
【问题描述】:

我想使用反射来动态填充我的复选框。

我找到了一个有帮助的答案here

并在我的代码中使用它:

    public static List<System.Type> getModuleList()
    {
        // fill with all Classes in Timestamp.View.UserControls.ModuleView per Reflection


        List<System.Type> theList = Assembly.GetExecutingAssembly().GetTypes()
                              .Where(t => t.Namespace == "Timestamp.View.UserControls.ModuleView")
                              .ToList();


        return theList;
    }

我填写了我的复选框,例如:

   foreach (System.Type type in ModuleController.getModuleList())
        {
            cbModule1.Items.Add(type);
            cbModule2.Items.Add(type);
            cbModule3.Items.Add(type);
            cbModule4.Items.Add(type);
        }
  1. 现在我想创建一个新的 SelectedType 实例

      private void CbModule4_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ucModul4.Content = //new Instance of Selected Item
    }
    

我可以使用反射创建一个新的实例,但我不知道如何。

  1. 我想给每个类一个字符串,它将在复选框中显示为项目。这是可能的,还是我需要一个方法来通过它的字符串找到一个类?

编辑:我需要争论为什么我的问题与 this one 不同

所以首先这个问题只能解决我的一个问题,但我更早发现它并没有帮助我。我不知道如何获取列表的类型以及如何为类指定别名。

【问题讨论】:

  • 不要对命名空间进行反射,定义一个共享接口,因为它们似乎都有一些共同点,然后只获取实现该接口的类型。然后你可以用类型化的方式填写你想要的属性,大概它们会有一个标签和一个选中的属性
  • @Icepickle 他们都有一个名为 IModuleView 的共享接口。但是我如何让所有类实现这个接口?

标签: c# wpf .net-4.0 system.reflection


【解决方案1】:

因为将Type 添加到组合框会生成type.ToString() 并将字符串表示形式放入combobox,所以您可以使用

var instance = Activator.CreateInstance(Type.GetType(cbModule4.SelectedText))

传递类型时,可以这样做:

var instance = Activator.CreateInstance(theList[0]))

【讨论】:

  • 我不能覆盖 type.ToString() 对吧?
  • 您可以将辅助类(如 ComboItem)及其实例放入组合框
  • 好主意,谢谢:)
  • @itskajo 你需要一个例子吗?
  • 不,谢谢 :) 我写了一个小类做这个:)
猜你喜欢
  • 2010-12-22
  • 2018-10-11
  • 2010-09-09
  • 2015-08-23
  • 1970-01-01
  • 2011-03-22
  • 2012-08-05
  • 2020-12-18
  • 2018-07-18
相关资源
最近更新 更多