Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 创建新对象C#_Oop_C# 4.0_Inheritance - Fatal编程技术网

Oop 创建新对象C#

Oop 创建新对象C#,oop,c#-4.0,inheritance,Oop,C# 4.0,Inheritance,A类:- class classOne { public int intOne = 0; public int Sub() { return 1; } public virtual int Add() { return 1; } } 第二类:- class classTwo:classOne { public new int Sub() { return 2; }

A类:-

class classOne
{
    public int intOne = 0;
    public  int Sub()
    {
        return 1;
    }
    public virtual int  Add()
    {
        return 1;
    }
}
第二类:-

class classTwo:classOne
{
    public new int Sub()
    {
        return 2;
    }
    public override int Add()
    {
        return 2;
    }

}
三班

class classThree : classTwo
{
    public int Sub()
    {
        return 3;
    }

}
Program.cs

classOne obj = new classOne();
classThree obj3 = new classThree();
obj = obj3;
Console.WriteLine(obj.Sub());
输出为1


我的疑问是我用classOne初始化了一个obj,然后我用new关键字
ClassThree obj3=newclassthree()将同一个对象分配给ClassThree。它如何调用
classOne.sub()
。这是怎么发生的?我的理解是,它应该调用classThree.Sub()

您没有将
Sub
设置为虚拟,因此编译器将使用变量的静态类型来确定要调用的实例。由于
obj
的静态类型是
classOne
,它将调用
classOne.Sub()

,这就是为什么在类2中的
Sub
重新声明中必须使用
new
关键字的原因。您显式地屏蔽了类1的方法。这里不使用继承或多态。您应该在一个.Sub声明中添加
virtual
,在两个.Sub声明中删除
new
,并在两个.Sub和三个.Sub声明中添加
override
这里我们将新类型引用到obj。在这种情况下,对象类型应该更改吗?为什么没有发生?为什么它仍然在ClassOne中?@Dhinesh-无论您分配给
obj
什么,编译器都会根据
obj
的静态类型做出方法调用决策。运行时类型仅在调用虚拟方法时使用<代码>添加
是虚拟的,因此编译器将调度到正确的版本
Sub
不是虚拟的,因此编译器将始终调用
classOne
实例。@Dhinesh-so,如果要调用被重写的
Sub
版本,请在基类中将其设为虚拟的。为什么你要编写<代码>添加<代码>虚拟,而不是<代码>子< /代码>?@肖恩认为,如果两者都<代码> ClassOne < /代码>和<代码> CLSSTWOW/<代码>是空的,但是<代码> CLSSTWOW/<代码>是从<代码> ClassOne < /C> >继承的。在这种情况下,首先使用
ClassOne
初始化一个对象,然后使用
ClassTwo
通过
new
关键字初始化同一个对象。现在根据
new
关键字,我们为
ClassOne
对象分配了新的引用,那么为什么该对象的类型仍然保持为
ClassOne
不变?