假设我们有这个界面:
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/