为什么人们声明他们分配给它的对象的基本类型的变量?

时间:2016-07-08 18:13:09

标签: c# class object inheritance

以下是一个例子:

abstract class baseClass
{
  void aMethod
  {
    //something here...
  }
}

class derivedClass : baseClass
{
  void aMethod
  {
    //something here...
  }
}

void main()
{
  baseClass Object_1 = new derivedClass();
}

为什么Object_1声明为baseClass?程序员为什么这样做? Object_1是什么类型的?是baseClass还是derivedClass?如果我的Object_1是这样创建的,那会有什么不同:

derivedClass Object_1 = new derivedClass();

我正在学习C#,在这种情况下,这是我最感兴趣的环境。

2 个答案:

答案 0 :(得分:1)

  

为什么使用baseClass类初始化Object_1?

不是。看一下new之后的类型,它是派生类型。你在这里得到的是使用基类型作为引用类型引用的派生类型实例。

  

程序员为什么这样做?

使用类型化引用意味着您可以使用对象的成员。根据使用的层次结构的实际类型,您可以访问相应的成员集。

Derived o = new Derived()
o.xxx  <- full access to instance members

Base o = new Derived()
o.xxx. <- access is limited to members that are defined in the Base class

object o = new Derived()
o.xxx. <- you can always see an instance as of 'object' type
          and have most limited interface

请注意,每次实例的实际类型为Derived时,由于某种原因,您决定通过不同的眼镜&#34;来查看它。

  

Object_1是什么类型

实际类型始终是new运算符之后的实际类型。

  

如果我的Object_1是这样创建的,那会有什么不同:

实例本身没有区别,但您有不同的方式来访问其成员。在像C#这样的语言中,您始终可以安全地将实例强制转换为其基本类型(或层次结构中的任何类型),但请注意,您不能总是在层次结构中执行相同的操作:

Derived1 d = new Derived1();
Base     b = (Base)d;

// d and b point to the very same instance but they differ on what properties you are allowed to access

Derived2 d2 = (Derived2)b;

// casting to a derived type would work only if the instance was of this actual type
// in a worst case such cast would then end with a run-time error

答案 1 :(得分:1)

一个实际示例:您希望将一组内容传递给方法。该方法应该对每件事做点什么。

在将集合传递给方法之前,必须创建它。要创建一组东西,您需要一个具有Add方法的类。列表类可以。

对于接收方法,将内容添加到集合的功能是无关紧要的。它只需要能够枚举集合中的东西。所以你传递了IEnumerable,而不是List。

通常,将实例分配给基本类型变量可以消除噪音并缩小做出假设的空间。它说“在这一点上,子类型并不重要,所以这并不比基本类型复杂。”这简化了思想。

相关问题