C# 每次反射在命名空间中获取 类 的列表
C# Get a List of Classes in a Namespace per Reflection
我想使用反射来动态填充我的复选框。
我找到了一个有用的答案 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);
}
现在我想创建 SelectedType 的新实例
private void CbModule4_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ucModul4.Content = //new Instance of Selected Item
}
我可以使用反射来创建一个新的实例,但我不知道如何。
- 我想给每个 Class 一个字符串,它将在复选框中显示为项目。这是可能的,还是我需要一种方法来通过其字符串找到 Class?
编辑:我需要争论为什么我的问题不同于 this one
所以首先这个问题只能解决我的一个问题,但是我发现它比较早,它并没有帮助我。我不知道如何获取列表的类型以及如何给 class 一个别名。
因为将 Type
添加到组合框会生成 type.ToString()
并将字符串表示形式放入 combobox
,您可以使用
var instance = Activator.CreateInstance(Type.GetType(cbModule4.SelectedText))
传递类型时,你可以这样做:
var instance = Activator.CreateInstance(theList[0]))
我想使用反射来动态填充我的复选框。
我找到了一个有用的答案 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);
}
现在我想创建 SelectedType 的新实例
private void CbModule4_SelectionChanged(object sender, SelectionChangedEventArgs e) { ucModul4.Content = //new Instance of Selected Item }
我可以使用反射来创建一个新的实例,但我不知道如何。
- 我想给每个 Class 一个字符串,它将在复选框中显示为项目。这是可能的,还是我需要一种方法来通过其字符串找到 Class?
编辑:我需要争论为什么我的问题不同于 this one
所以首先这个问题只能解决我的一个问题,但是我发现它比较早,它并没有帮助我。我不知道如何获取列表的类型以及如何给 class 一个别名。
因为将 Type
添加到组合框会生成 type.ToString()
并将字符串表示形式放入 combobox
,您可以使用
var instance = Activator.CreateInstance(Type.GetType(cbModule4.SelectedText))
传递类型时,你可以这样做:
var instance = Activator.CreateInstance(theList[0]))