c# - 我怎样才能得到哪个类已传递给方法

标签 c# .net

我有一个类有 9 个不同的属性,每个属性都是一个类

public class Vehicles
{
  Car car; //class
  Train train;  //class
  Plane plane; //class
}  

我将这个 Vehicle 对象传递给一个方法

例如

var Vehicles = new Vehicles();
Vehicles.Car = new Car()
Object1.WorkOutTransport(vehicle)

我需要在 Object1 中做的是在不使用 switch 语句的情况下实例化“车辆”并检查其他语句是否为空

这不是“家庭作业问题”...我已将其简化以仅说明问题

实际的车辆类有 9 个可以实例化的可能类

最佳答案

我建议重新考虑您的设计。

为什么不让所有车辆类型都实现一个通用接口(interface) IVehicle,然后让您的 Vehicles 类具有一个名为 Vehicle 的属性。

您只需担心一个属性。

public Interface IVehicle 
{
    ... //Properties Common to all vehicles
}

public class Car : IVehicle
{
    ... //Properties to implement IVehicle
    ... //Properties specific to Car
}

public class Vehicles
{
    public IVehicle Vehicle { get; set; }
}

var vehicles = new Vehicles();
vehicles.Vehicle = new Car();
... //Do whatever else you need to do.

关于c# - 我怎样才能得到哪个类已传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812874/

相关文章:

.net - 将一个控件置于另一个控件的中心

.net - Unity IOC 静态工厂

c# - 将 Newtonsoft JSON 序列化为字节数组

java - 为什么无法在托管环境中测量对象大小?

c# - 动态面板元素添加和滚动条

c# - 字符串表达式

c# - 使用 RegEx 进行多模式匹配

.net - 如何重构紧耦合类?

.net - 具有扎实的 WPF/.NET 背景学习 ASP.NET MVC

.net - 如何将事件回调中的数据返回到 Blazor 中的 JS 互操作方法