Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the C# virtual method

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to understand the virtual method of C#. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

When a method declaration in a class is preceded by a virtual modifier, we call it a C # virtual method, and vice versa. After the virtual modifier is used, no more static, abstract, or override modifiers are allowed. For a non-virtual method, whether it is called by an instance of the class to which it belongs, or by an instance of a derived class of that class, the method is executed in the same way. For virtual methods, the way they are executed can be changed by derived classes, and this change is achieved by overloading the method.

The following example illustrates the difference between C# virtual methods and non-virtual methods.

Example:

Using System; class A {public void F () {Console.WriteLine ("A.F");} public virtual void G () {Console.WriteLine ("A.G");}} class b=new A {new public void F () {Console.WriteLine ("B.F");} public override void G () {Console.WriteLine ("B.G");}} class Test {static void Main () {B b=new B () A. A. F (); B. F (); A. G (); b. G ();}}

In the example, class A provides two methods: non-virtual F and C # virtual method G. Class B provides a new non-virtual method F, which overrides the inherited F, and class B also overloads the inherited method G. Then the output should be:

A.F

B.F

B.G

B.G

Notice that in this example, the method a.G () actually calls B.G instead of A.G. This is because the compile-time value is A, but the runtime value is B, so B completes the actual call to the method.

The above is the editor for you to share how to understand the C# virtual method, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report