简体   繁体   English

如何区分亚型?

[英]How to differentiate between subtypes?

Assume we have a collection of vehicles. 假设我们有一些车辆。 The vehicles may be a bicycle, motorbike or car. 车辆可以是自行车,摩托车或汽车。

Now every car in this collection should have its windows cleaned. 现在,此系列中的每辆汽车都应清洁窗户。

There is a WindowCleaner that receives this collection of vehicles. 有一个WindowCleaner可以接收这些车辆集合。 How can he tell which vehicle needs its windows cleaned? 他怎么知道哪辆车需要清洁车窗? I see that if I differentiate between the vehicle subtypes in the WindowCleaner I will violate the open-closed principle. 我看到,如果在WindowCleaner中区分车辆子类型,则会违反开闭原理。

How else could one do this? 还有谁能做到这一点? Introduce an abstract bool property NeedsWindowsCleaned and then cast to the subtype? 引入一个抽象的bool属性NeedsWindowsCleaned,然后转换为子类型? This looks to me like type introspection in disguise. 在我看来,这似乎是变相的内省型。

using System;
using System.Collections.Generic;

namespace Dirty
{
    class Program
    {
        static void Main()
        {
            var vehicles = new List<Vehicle>();

            var bike = new Bicycle();
            var motorbike = new Motorbike();
            var car = new Car();

            vehicles.Add(bike);
            vehicles.Add(motorbike);
            vehicles.Add(car);

            foreach (var v in vehicles)
            {
                if (v.CleanWindows())
                {
                    Console.WriteLine("{0}", v);
                }
            }

            Console.ReadKey();
        }
    }

    class Vehicle
    {
        public virtual bool CleanWindows()
        {
            return false;
        }
    }

    class Bicycle : Vehicle
    {

    }

    class Motorbike : Vehicle
    {

    }

    class Car : Vehicle
    {
        public override bool CleanWindows()
        {
            return true;
        }
    }
}

I think this might do what you are after - all the classes inherit from "Vehicle" & can optionally override the virtual "CleanWindows" method ... if they don't they get the default "false" 我认为这可能会完成您的工作-所有类均继承自“ Vehicle”,并且可以有选择地覆盖虚拟的“ CleanWindows”方法...如果不这样做,它们将获得默认的“ false”

I hope I haven't misunderstood - I am new to all this :) 我希望我没有被误解-我是这一切的新手:)

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

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