ConsoleApplication2
{
    class Program
    {
    
        
static void Main(string[] args)
        {
            MyDerivedClass MyObj 
= new MyDerivedClass();
            IMyInterface MyInt 
= MyObj;
            MyInt.DoSomething();
        }
    }
    
public interface IMyInterface
    {
        
void DoSomething();
        
void DoSomethingElse();
    }
    
public class MyBaseClass : IMyInterface
    {
        
public virtual void DoSomething()
        {
            Console.WriteLine(
"Base");
        }
        
public virtual void DoSomethingElse()
        {
            Console.WriteLine(
"BaseElse");
        }
    }
    
public class MyDerivedClass : MyBaseClass
    {
        
public new void DoSomething()
        {
            Console.WriteLine(
"Derived");
        }
        
public  override void DoSomethingElse()
        {
            Console.WriteLine(
"DeriveElse");
        }
    }
}

 

 

  • virtual可以重写
  • abstract必须重写(只用于抽象类中)
  • override实现重写基类方法的操作
  • extern在类外定义

     

     

    输出结果为:

    base

    如果是

    Code

     Derived

     ConsoleApplication2
    {
        class Program
        {
        
            
    static void Main(string[] args)
            {
                MyDerivedClass MyObj 
    = new MyDerivedClass();
                IMyInterface MyInt 
    = MyObj;
                MyInt.DoSomething();
            }
        }
        
    public interface IMyInterface
        {
            
    void DoSomething();
            
    void DoSomethingElse();
        }
        
    public class MyBaseClass : IMyInterface
        {
            
    public virtual void DoSomething()
            {
                Console.WriteLine(
    "Base");
            }
            
    public virtual void DoSomethingElse()
            {
                Console.WriteLine(
    "BaseElse");
            }
        }
        
    public class MyDerivedClass : MyBaseClass,IMyInterface
        {
            
    public new void DoSomething()
            {
                Console.WriteLine(
    "Derived");
            }
            
    public  override void DoSomethingElse()
            {
                Console.WriteLine(
    "DeriveElse");
            }
        }
    }

    new起到隐藏的作用,使用方法的时候具体调用哪个看声明而不是值

     

     

  • 相关文章: