代码之家  ›  专栏  ›  技术社区  ›  Sonic Soul

永久铸造成超玻璃

  •  5
  • Sonic Soul  · 技术社区  · 15 年前

    如果:

    class Car : Automobile
    {}
    

    我能做到:

    Car toyota = new Car();
    Automobile tauto = (Automobile)toyota;
    

    tauto.GetType().Name 还是会的 小型车 .

    我试图克服的问题是,c中没有多重继承,我需要在一个方法中合并来自2个服务的对象(具有相同签名),并返回一个类型。

    5 回复  |  直到 12 年前
        1
  •  11
  •   Reed Copsey    15 年前

    不,如果不构建 汽车物体。

    Liskov substitution principle 说任何 Car 应该,总是,像 Automobile

    只要正确地设计类层次结构,就可以使用 作为 应该是完全可以接受的。


    附带说明:这是使用 Type.GetType() is as C#中的关键字。如果你检查的话他们会返回真的 tauto is Car .

        2
  •  0
  •   Matthew Graybosch    15 年前

    根据 MSDN 参考

        3
  •  0
  •   Will    15 年前

    你的问题和你想做的似乎是两码事。不,不能更改对象的基本类型。但您似乎想做的是创建一种具有一组属性的汽车类型,而不是实际使用子类。你能做的是用一家汽车厂代替。

    public static class AutomobileFactory()
    {
       public static Automobile CreateAutomobile(AutomobileType type)
       {
         ...   
       } 
    }
    

    其中AutomobileType是枚举。有关更多信息,请访问google C#Factory pattern。

        4
  •  0
  •   Brandon    15 年前

    我不知道你到底想干什么,但也许你可以考虑换个方法?与其尝试使用继承来合并两个不同类的功能,不如使用composition?

    http://tiedyedfreaks.org/eric/CompositionVsInheritance.html

    public class Service
    {
        public virtual void DoSomething()
        {
    
        }
    }
    
    public class ServiceA : Service
    {
        public override void DoSomething()
        {
    
        }
    }
    
    public class ServiceB : Service
    {
        public override void DoSomething()
        {
    
        }
    }
    
    public class ServiceA_B : Service
    {
        ServiceA serviceA = new ServiceA();
        ServiceB serviceB = new ServiceB();
    
        public override void DoSomething()
        {
            serviceA.DoSomething();
            serviceB.DoSomething();   
        }
    }
    
        5
  •  0
  •   supercat    15 年前

    在某些情况下,泛型可能会有帮助。如果方法包含泛型参数,则泛型类型将被计算为传入引用的声明类型,而不是传入对象的类型。例如:

    void Foo(T bar)