我需要澄清一个对象类型变量如何接受下面代码片段中给定的类类型实例,
class MyClass
{
}
static void Main()
{
object obj = new MyClass();
}
由于 MyClass 不是一种对象类型,但 MyClass 的实例仍然在 obj(object) 变量中被接受。
我需要澄清一个对象类型变量如何接受下面代码片段中给定的类类型实例,
class MyClass
{
}
static void Main()
{
object obj = new MyClass();
}
由于 MyClass 不是一种对象类型,但 MyClass 的实例仍然在 obj(object) 变量中被接受。
Actually, your class is an object.
In C# all classes derives from object.
Referring to a class as it's base type is one way of Polymorphism.
It might be better understood using an analogy:
Your class is an object, like a Dog is an animal.
Also, If you try the following:
object obj = new MyClass();
bool isMyType = obj == typeof(MyClass); //<--this will be true.
Take a look at this SO thread for more information how Polymorphism can be useful.
The concept that you do not understand is polymorphism which basically say that you can define an is
relation between your classes. For a simple logic every dog is an animal so you can have class Dog
that inherits from Animal
. This implies that you can assign to variable of type Animal
an instance of a Dog
but not the other way around - not every animal is a dog. Another thing is that every thing derives form object this is language concept that you simply can take for granted.
c# 中的所有东西都派生自Object ……甚至是你的类。
MSDN:
Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Inheritance Hierarchy:
All classes, structures, enumerations, and delegates.
This means when you use int.Parse()
to cast some value to int
, there is a class behind int
type which makes it able to have methods and do such stuffs. Object
has been rooted pretty much everywhere in .Net.
.Net
遵循OOPs
(面向对象的编程语言),这里每个类都可以作为一个对象。每个类都继承Object 类,因此每个类都可以充当对象。在您的示例中,.Net 创建一个默认构造函数来创建该类的实例。您绝对可以在那里编写自己的构造函数。
希望能帮助到你。