对象=新的狗()VS狗=新的狗之间的差异() [英] Difference between object a = new Dog() vs Dog a = new Dog()
本文介绍了对象=新的狗()VS狗=新的狗之间的差异()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
object a = new Dog();
VS
vs
Dog a = new Dog();
在这两种情况下 a.GetType()
给狗
。
都调用相同的构造(相同的层次结构)。
In both cases a.GetType()
gives Dog
.
Both invoke same constructor (with same hierarchy).
然后可以请你告诉我,这两个语句之间的区别?
Then can you please tell me the difference between these two statements?
推荐答案
这两个创建一个Dog对象。只有第二个允许你直接调用狗的方法或以其他方式对待它像狗,例如,如果你需要将对象传递给方法作为类型的参数狗
(或东西在狗的层次结构是不是简单地对象更具体
)。
Both create a Dog object. Only the second allows you to directly invoke Dog methods or to otherwise treat it like a dog, such as if you need to pass the object to a method as a parameter of type Dog
(or something in the Dog hierarchy that is more specific than simply object
).
object obj = new Dog();
// can only see members declared on object
var type = obj.GetType(); // can do this
Console.WriteLine(obj.ToString()); // also this
obj.Bark(); // Error! Bark is not a member of System.Object
Dog dog = new Dog();
// can do all of the methods declared for Object
dog.Bark(); // can finally use the method defined for Dog
这篇关于对象=新的狗()VS狗=新的狗之间的差异()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文