[英]Which is valid object in C#?
I have one base class Base and a class Derived1 which is derived from Base class and another derived class Derived2 which is dervied from derived1 . 我有一个基类Base和一个Derived1类,它派生自Base类,另一个派生类Derived2派生自derived1 。
Below i have mentioned few cases of object creation ( following by Multilevel inheritance of class ). 下面我提到了几个对象创建的例子(后面是类的多级继承)。 Can someone help me in understanding those cases in which object creation is not possible and why it is not possible in C# ?
有人可以帮助我理解那些无法创建对象的情况以及为什么在C#中无法实现对象?
Base b1 = new Base() //Possible
Base b1 = new derived1() // Possible
Derived1 d1 = new Base() // Not Possible
Derived1 d1 = new Derived1() // Possible
Derived2 d2 = new Derived1() // ----
Derived1 d1 = new Derived2() // ----
Derived2 d2 = new Derived2() // Possible
Derived2 d2 = new Base() // ----
Base b1 = new Derived2() // ----
Here is a super easy way: 这是一个超级简单的方法:
public class A { }
public class B : A { }
public class C : B { }
So it's as simple as reversing the definitions: 所以它就像撤消定义一样简单:
A < B < C
(I'm using the greater than sign here, because B is everything A is and more. C is everything B and A are... and more.) (我在这里使用大于号,因为B就是A和A的所有东西.C是B和A的所有东西......等等。)
So A can support A, B and C. And B can support B and C. Lastly C can only support C. 所以A可以支持A,B和C.B可以支持B和C.最后C只能支持C.
Valid: 有效:
A z = new A();
A y = new B();
A x = new C();
B w = new B();
B v = new C();
C u = new C();
Any other combination is not supported by C# (because of Liskov's substitution principle ). C#不支持任何其他组合(因为Liskov的替换原则 )。
Derived class has all the information about the base class, as inheritance is a "is-a" relationship. 派生类具有关于基类的所有信息,因为继承是“is-a”关系。
We have a base class "Base" and a derived class "Derived" 我们有一个基类“Base”和派生类“Derived”
according to inheritance rule "Derived is-a Base". 根据继承规则“Derived is-a Base”。 All the properties of Base is present in Derived.
Base的所有属性都存在于Derived中。
Base b = new Derived(); 基数b = new Derived(); //It is possible as Derived as all the information about base.
//可以像Derived一样获得有关base的所有信息。
Dervied d = new Base(); Dervied d = new Base(); //It is not possible because base don't have the information about derived.
//这是不可能的,因为base没有关于派生的信息。
That's easy. 这很简单。 The reference (variable declared, so left hand side) must be of less derived type.
引用(声明的变量,因此左侧)必须是较少的派生类型。 The instance on the right side may be more derived.
右侧的实例可能更加派生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.