c# - 在解决方案中显示类名的 ComboBox 项

标签 c# winforms visual-studio

我有一个公共(public)抽象类 Client,它有两个继承类 CustomerTimeWaster

我在 C# Windows Forms 上创建了一个下拉菜单,我想将这两个类名称显示为选项:Customer 和 TimeWaster。

我所能想到的就是创建一个包含这两个术语的简单List,然后将该列表绑定(bind)到组合框DataSource:

List<string> clientType = new List<string>()
{
    "Customer",
    "TimeWaster"
};

public frmClientScreen()
{
    cmboxClientType.DataSource = clientType;
}

但这不是可维护的,因为将来我可能会添加许多其他类,我希望它们的名称显示在下拉菜单中。

如何将我的 Visual Studio 解决方案 中的类名链接到组合框显示的项目?

最佳答案

获取一组已知类型的类型名称:

List<string> clientType = new List<string>()
{
    nameof(Customer),
    nameof(TimeWaster)
};

public frmClientScreen()
{
    cmboxClientType.DataSource = clientType;
}

关于动态获取从特定类型派生的所有类型,这 question显示了如何执行此操作的示例。

来自该问题的已接受答案:

var listOfBs = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                from assemblyType in domainAssembly.GetTypes()
                where typeof(B).IsAssignableFrom(assemblyType)
                select assemblyType).ToArray();

B 应替换为您的基类。

然后,在获取派生类型列表后,您可以执行以下操作:

var clientTypes = listOfBs.Select(x => x.Name).ToList();

关于c# - 在解决方案中显示类名的 ComboBox 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861379/

相关文章:

C# - 引用 "this int"参数

c# - 为什么 KeyValuePair<int, long> 是 16 个字节?

c# - 我可以在 WinForms 中的 PictureBox 上创建透明背景吗?

c# - 在设计模式下进行编辑时 designer.vb 文件中的自定义代码消失

visual-studio - Truecrypt 7.0 版本

c# - 检查用户是否在线mvc4

c# - Mathf.Clamp 在 Unity 3D 中将我的 eulerangle 重置为 minValue

.net - 使用.NET WinForm打印预览ZPL II命令,然后将其发送到Zebra打印机

c# - 错误 : multiple types matching the name while Scaffolding ASP. NET Core MVC RC2

visual-studio - 最有用的 Visual Studio 功能和工具