2

我需要澄清一个对象类型变量如何接受下面代码片段中给定的类类型实例,

class MyClass
{

}

static void Main()
{
   object obj = new MyClass();
}

由于 MyClass 不是一种对象类型,但 MyClass 的实例仍然在 obj(object) 变量中被接受。

4

6 回答 6

3

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.

于 2013-10-15T06:30:53.093 回答
2

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.

于 2013-10-15T06:31:12.600 回答
2

c# 中的所有东西都派生自Object ……甚至是你的类。在此处输入图像描述

于 2013-10-15T06:32:55.797 回答
1

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.

于 2013-10-15T06:32:07.157 回答
1

.Net遵循OOPs(面向对象的编程语言),这里每个类都可以作为一个对象。每个类都继承Object 类,因此每个类都可以充当对象。在您的示例中,.Net 创建一个默认构造函数来创建该类的实例。您绝对可以在那里编写自己的构造函数。

希望能帮助到你。

于 2013-10-15T06:26:43.733 回答
1

C# 中的所有内容都派生自Object

甚至像 struct(int,float,..) 这样的值类型都是从 Object 类型派生的。


当您定义自己的类时,它隐式地派生自 Object 类型。

它在文档中提到

所有类、结构、枚举和委托都继承自 Object 类

于 2013-10-15T06:28:12.713 回答