search
HomeBackend DevelopmentC#.Net TutorialVersioning with the Override and New Keywords (C# Programming Guide)

Original address: Click to open the link



##This has Many meanings. This means, for example, that introducing a new member in a base class with the same name as a member in a derived class is fully supported in C# and will not lead to unexpected behavior. It also means that the class must explicitly declare whether a method is to override an inherited method or a new method that hides an inherited method with a similar name.

In C#, a derived class can contain methods with the same names as base class methods.

  • #The base class method must be defined as virtual.

  • If a method in a derived class is not preceded by the new or override keyword, the compiler will issue a warning and the method will appear as if it exists new keyword performs the same operations.

  • If a method in a derived class is preceded by the new keyword, the method is defined as independent of the method in the base class .

  • If a method in a derived class is preceded by the override keyword, the object of the derived class will call the method instead of calling Base class methods.

  • You can use the base keyword to call base class methods from a derived class.

  • ##override, virtual and new keywords can also be used for attributes and indexes devices and events.

If a method is declared virtual, any class that inherits the method can implement its own version. To make a method a virtual method, you must use the virtual modifier in the method declaration of the base class. Then, the derived class can use the override keyword to override the base virtual method, or use the new keyword to hide the virtual method in the base class. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and methods in the derived class will hide methods in the base class.

GraphicsClass is as follows:

C



class GraphicsClass
{    public virtual void DrawLine() { }    public virtual void DrawPoint() { }
}


Your company uses this class, and you Use this to derive your own class when adding new methods:

C



class YourDerivedGraphicsClass : GraphicsClass
{    public void DrawRectangle() { }
}


Your application runs fine until Company A releases a new version of GraphicsClass, similar to the following code:

C




class GraphicsClass
{    public virtual void DrawLine() { }    public virtual void DrawPoint() { }    public virtual void DrawRectangle() { }
}


At the beginning, no problems occurred. The new version remains binary compatible with the old version. Any software that has been deployed will continue to work normally even if new classes are installed on the computer system where the software resides. In your derived class, any existing calls to method DrawRectangle will continue to reference your version.

This warning indicates that you must consider how you want the DrawRectangle method to work in your application.

If you want your method to override the new base class method, please use the override keyword:

C



#
class YourDerivedGraphicsClass : GraphicsClass
{    public override void DrawRectangle() { }
}


 派生自 YourDerivedGraphicsClass 的对象仍可以使用基关键字访问DrawRectangle 的基类版本

C#


base.DrawRectangle();


 为了避免这两个方法之间发生混淆,可以重命名您的方法。 这可能很耗费时间且容易出错,而且在某些情况下并不可行。 但是,如果您的项目相对较小,则可以使用 Visual Studio 的重构选项来重命名方法。 有关更多信息,请参见重构类和类型(类设计器)。

或者,也可以通过在派生类定义中使用关键字 new 来防止出现该警告:

C#


class YourDerivedGraphicsClass : GraphicsClass
{    public new void DrawRectangle() { }
}


 这是默认行为。

重写和方法选择

 下面的方法将是兼容的:

C#


public class Derived : Base
{    public override void DoWork(int param) { }    public void DoWork(double param) { }
}


 重写方法不被视为是在类上进行声明的,而是在基类上声明的方法的新实现。 仅当 C# 编译器无法将方法调用与 Derived 上的原始方法匹配时,它才尝试将该调用与具有相同名称和兼容参数的重写方法匹配。 例如:

C#



int val = 5;
Derived d = new Derived();
d.DoWork(val);  // Calls DoWork(double).


 有两种方法可以避免此情况。 首先,避免将新方法声明为与虚方法同名。 其次,可以通过将 Derived 的实例强制转换为 Base 来使 C# 编译器搜索基类方法列表,从而使其调用虚方法。 由于是虚方法,因此将调用 Derived 上的 DoWork(int) 的实现。 例如:

C#


((Base)d).DoWork(val);  // Calls DoWork(int) on Derived.


有关 new 和 override的更多示例,请参见 了解何时使用 Override 和 New 关键字(C# 编程指南)。

 以上就是使用 Override 和 New 关键字进行版本控制(C# 编程指南)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Building Microservices with C# .NET: A Practical Guide for ArchitectsBuilding Microservices with C# .NET: A Practical Guide for ArchitectsApr 06, 2025 am 12:08 AM

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

C# .NET Security Best Practices: Preventing Common VulnerabilitiesC# .NET Security Best Practices: Preventing Common VulnerabilitiesApr 05, 2025 am 12:01 AM

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.

In c language: What does it meanIn c language: What does it meanApr 03, 2025 pm 07:24 PM

The meaning of colon (':') in C language: conditional statement: separating conditional expressions and statement block loop statement: separating initialization, conditional and incremental expression macro definition: separating macro name and macro value single line comment: representing the content from colon to end of line as comment array dimension: specify the dimension of the array

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function