abstract virtual new

来源:互联网 发布:淘宝美工助理破解版 编辑:程序博客网 时间:2024/06/16 12:21

Here is the program and results, we will see how the virtual and new goes.

public class MyBase
    {
        public virtual string MyVirtualMethod()
        {
            return "Base";
        }

        public string MyNonVirtualMethod()
        {
            return "Base";
        }
    } //end of sub class

    public class MyDerived : MyBase
    {
        public override string MyVirtualMethod()
        {
            return "Derived";
        }

        public new string MyNonVirtualMethod()
        {
            return "Derived";
        }
    } //end of sub class

--------------------------------------------------------------------------------

MyBase m1 = new MyDerived();
Console.WriteLine("MyVirtualMethod='" + m1.MyVirtualMethod() + "', MyNonVirtualMethod='" + m1.MyNonVirtualMethod() + "'");
//    Returns: MyVirtualMethod='Derived', MyNonVirtualMethod='Base'

MyDerived md = new MyDerived();
Console.WriteLine("MyVirtualMethod='" + md.MyVirtualMethod() + "', MyNonVirtualMethod='" + md.MyNonVirtualMethod() + "'");
//    Returns: MyVirtualMethod='Derived', MyNonVirtualMethod='Derived'

----------------------------------------------------------------------------------

the difference bewteen abstract and virtual:

1. abstract method must use in the abstract class, and is required no implement.

2. in the derived class, both of them can be override.

   however, virtual method has other two choice, new and do nothing.

 VirtualAbstractHas implementationYesNoScopemembers onlymembers and classesCan create an instance ofNot Applicable (you can only create instances of classes, not members)No - but you can create an instance of a class that derives from an abstract class. And you can declare a type Abstract class and instantiate that as a derived class.

 

 

PS:

reference by http://timstall.dotnetdevelopersjournal.com/tips_with_oop__new_virtual_and_abstract.htm

原创粉丝点击