本文介绍了在C#中使用基类和子类的基类实例之间的用途和区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 BaseClass obj1 = new BaseClass(); BaseClass obj2 = new ChildClass(); 是什么让obj2特别优于obj1? 如果有任何场景可以使obj2特别请引用相同的内容。 我尝试了什么: 我试过初始化对象两种方式和使用方法,它的参数看起来都只有我。解决方案 没什么。 In事实上你可以这样做: BaseClass obj1 = new BaseClass(); BaseClass obj2 = new ChildClass(); obj1 = obj2; 发生的事情 继承 - ChildClass继承自BaseClass,因此它是带有额外内容的基类 - 每个实例同时都是一个ChildClass实例和一个BaseClass实例。 想想汽车片刻:你可以驾驶一辆汽车。这意味着你可以驾驶福特和梅赛德斯;此外,您还可以驾驶福特嘉年华,福特福克斯,梅赛德斯A级和布加迪威龙 - 您无需为每个制造商或每个车型进行新的测试。 焦点继承自福特,继承自汽车 A级继承自梅赛德斯,继承自汽车。 所以汽车可以做任何事情(StartTheEngine,DriveToTheShops)任何福特都可以做,任何福克斯或嘉年华也可以做。 返回计算机,它是一样的:你有一个基类,所有派生类都可以做基本所能做的一切。当你使用变量时,它的类型决定了编译器允许你做什么: BaseClass obj1 = new BaseClass(); BaseClass obj2 = new ChildClass(); obj1.BaseClassMethod(); obj2.BaseClassMethod(); 一切都很好。 但它不会让你使用ChildClass特定项目: obj1.ChildClassMethod(); obj2.ChildClassMethod(); 两者都会给你一个编译器错误,因为obj1和obj2都能够持有一个BaseClass,这并不意味着他们持有的将是一个ChildClass实例。 这有意义吗? BaseClass obj1 = new BaseClass();BaseClass obj2 = new ChildClass();what makes the obj2 special over obj1?if there is any scenario which can make obj2 special please quote the same.What I have tried:I have tried initializing object in both ways and using methods, parameters from it both looks similar only for me. 解决方案 Nothing.In fact you can do this:BaseClass obj1 = new BaseClass();BaseClass obj2 = new ChildClass();obj1 = obj2;What's happening is inheritance - ChildClass inherits from BaseClass, so it is "Base class with extras" - every instance is both a ChildClass instance and a BaseClass instance at the same time.Think about cars for a moment: You can drive a Car. Which means you can drive a Ford, and a Mercedes; and further you can drive a Ford Fiesta, and a Ford Focus, and a Mercedes A Class, and a Bugatti Veyron - you don't have to take a new test for each manufacturer or each model."Focus" inherits from "Ford", which inherits from "Car""A Class" inherits from "Mercedes", which inherits from "Car".So anything that a Car can do (StartTheEngine, DriveToTheShops) any Ford can do, and any Focus or Fiesta can also do.Back to computers, and it's the same thing: You have a base class and all derived classes can do everything that the base can. When you use the variable, it's type determines what the compiler will let you do: BaseClass obj1 = new BaseClass();BaseClass obj2 = new ChildClass();obj1.BaseClassMethod();obj2.BaseClassMethod();All perfectly fine.But it won't let you use ChildClass specific items:obj1.ChildClassMethod();obj2.ChildClassMethod();Both will give you a compiler error because obj1 and obj2 are both capable of holding a BaseClass which doesn't mean that what they hold will be a ChildClass instance.Does that make any sense? 这篇关于在C#中使用基类和子类的基类实例之间的用途和区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-29 21:12