繁体   English   中英

如何获取已传递给方法的类

[英]how can I get which class has been passed to method

我有一个有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语句的情况下实例化'vehicle'的训练并检查其他是否为null

这不是一个“功课问题”......我简化了它只是为了说明问题

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

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

为什么不让所有车型都实现通用接口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.

假设只有一个非null,您可以这样做:

Vehicle instance = vehicle.Car ?? vehicle.Train ?? vehicle.Plane;

但是如果你想对你的instance做任何有用的事情,你就必须检查typeof(instance)并将其转换为正确的类。

您可能想要考虑只有一个属性:

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

并移动功能,以便您的WorkOutTransport方法可以作用于Vehicle实例,而不是关心它具有哪个子类。 Vehicle类中使用virtual方法或abstract方法,并在子类中override它们。

如果使用不同的属性,则无法避免检查哪个为null。 我建议一个基类,它具有标识类型的属性或覆盖ToString方法。

您可以强制接口继承者指定其类型:

enum VehicleType
{
    Passenger,
    Truck,
    // Etc...
}

public Interface IVehicle 
{
    VehicleType Type { get; }
    ... // Properties Common to all vehicles
}

public sealed class Truck : IVehicle
{
    // ... class stuff.

    // IVehicle implementation.
    public VehicleType Type { get { return VehicleType.Truck; } }
}

这将允许您不要查看每个类,而是要确切知道要转换的类型。

IVehicle vehicle = GetVehicle();

switch (vehicle.Type)
    case (VehicleType.Truck)
    {
        // Do whatever you need with an instance.
        Truck truck = (Truck)vehicle;
        break;
    }
    // ... Etc

除了switch之外,你还有其他任何一个appoarch。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM