个性化阅读
专注于IT技术分析

C#中的方法重写和方法隐藏之间的区别

点击下载

方法重写是一种允许从派生类中的另一个类(基类)调用函数的技术。在派生类中创建与基类中的方法具有相同签名的方法称为方法覆盖.

简而言之, Overrideing是一项功能, 它允许子类或子类提供其超类或父类之一已经提供的方法的特定实现。当子类中的方法与其父类中的方法具有相同的名称, 相同的参数或签名以及相同的返回类型(或子类型)时, 则称子类中的方法覆盖父类中的方法-类。

例子:

//C# program to illustrate the 
//Method overriding concept
using System;
  
//Base class
class My_Parent {
  
     //virtual method
     public virtual void display()
     {
         Console.WriteLine( "My new parent class.. !" );
     }
}
  
//Derived class
class My_Child : My_Parent {
  
     //Here display method is overridden
     public override void display()
     {
         Console.WriteLine( "My new child class.. !" );
     }
}
  
class GFG {
  
     //Main Method
     public static void Main()
     {
  
         My_Parent obj;
  
         //Creating object of the base class
         obj = new My_Parent();
  
         //Invoking method of the base class
         obj.display();
  
         //Creating object of the derived class
         obj = new My_Child();
  
         //Invoking method of derived class
         obj.display();
     }
}

输出如下:

My new parent class.. !
My new child class.. !

在方法隐藏中, 你可以使用来从派生类中隐藏基类方法的实现。新关键词。换句话说, 在方法隐藏中, 你可以使用new关键字在派生类中重新定义基类的方法。

例子:

//C# program to illustrate the
//concept of method hiding
using System;
  
//Base Class
public class My_Parent {
  
     public void show()
     {
         Console.WriteLine( "This is my parent class." );
     }
}
  
//Derived Class
public class My_Child : My_Parent {
  
     //Hide the method of base class
     //Using new keyword
     public new void show() {
  
         Console.WriteLine( "This is my child class." );
     }
}
  
public class GFG {
  
     //Main method
     static public void Main()
     {
  
         //Creating the object of 
         //the derived class
         My_Child obj = new My_Child();
  
         //Access the method of derived class
         obj.show();
     }
}

输出如下:

This is my child class.

方法覆盖与方法隐藏

方法覆盖 方法隐藏
在方法覆盖中, 你需要使用virtual关键字将父类的方法定义为虚拟方法, 而使用override关键字将子类的方法定义为覆盖方法。 在方法隐藏中, 你只需在父类中创建一个方法, 而在子类中, 你需要使用new关键字定义该方法。
它仅重新定义了该方法的实现。 在方法隐藏中, 你可以完全重新定义方法。
这里的重载是一个对象类型。 隐藏在这里是引用类型。
如果不使用override关键字, 则编译器将不会覆盖该方法。而不是覆盖编译器将隐藏该方法。 如果不使用new关键字, 则编译器将自动隐藏基类的方法。
在方法重写中, 当基类引用变量指向派生类的对象时, 它将在派生类中调用被重写的方法。 在方法隐藏中, 当基类引用变量指向派生类的对象时, 它将在基类中调用隐藏方法。

赞(0)
未经允许不得转载:srcmini » C#中的方法重写和方法隐藏之间的区别

评论 抢沙发

评论前必须登录!