c# - 如何根据对象的类型创建 WinForms 组件

标签 c# winforms user-controls types

假设我们有这个界面:

interface IVehicle { ... }

以及一些实现它的类:

class Car : IVehicle { ... }
class Boat : IVehicle { ... }
class Plane : IVehicle { ... }

在我的用户界面中,我有一个 FlowLayoutPanel并访问某种IEnumerable<IVehicle>与许多不同的IVehicle对象。

现在我想创建一个UserControl对于每辆车并将其添加到 FlowLayoutPanel 。这些控件会有点相似,但由于存在不同类型的车辆,某些控件可能需要看起来略有不同或以不同的方式工作,以便用户可以轻松地使用他的车辆。我怎样才能在没有太多困惑的情况下最好地解决这个问题?

最佳答案

使用某种工厂方法怎么样:

UserControl CreateControl(IVehicle vehicle) 
{
    if (vehicle is Car)
    {
        return new CarControl();
    }
    else if (vehicle is Boat)
    {
        return new BoatControl();
    }
    ...
}

关于c# - 如何根据对象的类型创建 WinForms 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1226529/

相关文章:

c# - 将图像嵌入文本框

user-interface - 3 路输入的用户界面元素 : yes, 不,不关心

c# - 使用 MySQL 在 ASP.NET 中登录错误

c# - 从 MemoryStream 运行 Microsoft Excel 应用程序

c# - 如何在后面的代码中使文本框只读属性为 false?

c# - 控制音量混合器

c# - 我如何判断我的程序是否是焦点程序?

c# - 如何在 DataContext 略有不同的情况下重用 UserControl?

.net - 创建 C++ 控件并在 C# 中使用它可以获得性能吗?

c# - 带 UltraMaskedEdit 的时间选择器 (hh :MM tt) changes format to HH:MM when entering into edit mode