Virtual method overload in C #

Source: Internet
Author: User
In C #, the overload of the virtual method has some experience, now share with you.
First of all, please take a look at the following example,
Using System;

Abstract public class contacts
{
Public virtual string Prinf ()
{
Return ("This is a virtual method");
}
}

public class Class1:contact
{
public string Prinf ()
{
Return ("This is the New method");//But this will result in a compilation warning because a method with the same name has been inherited from the contact
}
}
To compile, simply change the Prinf declaration to
public override string Prinf ()
Or
Public new string Prinf ()
But there is a difference between these two ways of declaring,
Take a look at the following example:
Using System;

Abstract public class contacts
{
Public virtual string Prinf ()
{
Return ("This is a virtual method");
}
}

public class Class1:contact
{
public override string Prinf ()
{
Return ("This is the New method");
}
}
public class Class2:contact
{
Public new string Prinf ()
{
Return ("This is another new method");
}
}
public class text
{
public static void Main ()
{
Contact [] contacts=new contacts [2];
Contacts[0]=new Class1;
Contacts[1]=new Class2;
foreach (Contact CT in Contacts)
{
Console.WriteLine (ct.printf);
}
}
}

Finally, the result we see is

This is the new way.
It's a virtual method.


Instead of seeing "this is another new method", this is because Class2 has not overloaded the virtual method, but redefined a method!
That's the difference between the two!!!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.