2012-10-02 31 views
2

可能重复:
What are Virtual Methods?为什么虚方法

在C#中,即使你不申报的基类方法,如虚拟化,编译器总是调用最新的派生类的方法时,方法签名匹配。 如果没有virtual关键字,我们只会得到警告消息,说明派生方法将被调用(现在可以通过使用new关键字来删除)。

当没有这个关键字时,声明该方法为virtual的用法也是当签名匹配时调用最后一个派生类中的方法。

我不理解这里的东西。代码可读性的目的是“虚拟”吗? Smith

+1

[MSDN:虚拟](http://msdn.microsoft.com /en-us/library/9fkccyh4(v=vs.71).aspx) –

+1

你在说_shadowing_。这与重写不同。请参见[MSDN](http://msdn.microsoft.com/zh-cn/library/ms172785.aspx)和[here](http://stackoverflow.com/questions/392721/difference-between-shadowing-and -over-in-in-c) – Oded

回答

0

虚拟方法可以重新定义。在C#语言中,virtual关键字指定了可以在派生类中重写的方法。这使您可以添加新的派生类型,而无需修改程序的其余部分。对象的运行时类型因此决定了程序的功能。

你可以看到一个细节example

public class Base 
{ 
    public int GetValue1() 
    { 
    return 1; 
    } 

    public virtual int GetValue2() 
    { 
    return 2; 
    } 
} 

public class Derived : Base 
{ 
    public int GetValue1() 
    { 
    return 11; 
    } 

    public override int GetValue2() 
    { 
    return 22; 
    } 
} 

Base a = new A(); 
Base b = new B(); 

b.GetValue1(); // prints 1 
b.GetValue2(); // prints 11 
+0

我明白“虚拟”方法的工作原理。我的观点是没有这个关键字的行为是相同的,除了一个警告信息。换句话说,我可以在不使用关键字的情况下获得“虚拟”方法实施的全部好处。使用这个关键字是更好的做法吗? – user1492518

+0

不,事情工作完全不同。 “虚拟”不是句法糖。请阅读我的回复。 –

+0

@ user1492518看看这个例子。 –

5

它不是真的关于“最新派生的方法”。这是关于当你使用多态时会发生什么。当您在预期父类的上下文中使用派生类的实例时,如果您不使用virtual/override,它将调用父类的方法。

实施例:

class A 
{ 
    public int GetFirstInt() { return 1; } 
    public virtual int GetSecondInt() { return 2; } 
} 

class B : A 
{ 
    public int GetFirstInt() { return 11; } 
    public override int GetSecondInt() { return 12; } 
} 

A a = new A(); 
B b = new B(); 

int x = a.GetFirstInt(); // x == 1; 
x = a.GetSecondInt(); // x == 2; 
x = b.GetFirstInt();  // x == 11; 
x = b.GetSecondInt(); // x == 12; 

但有以下两种方法

public int GetFirstValue(A theA) 
{ 
    return theA.GetFirstInt(); 
} 

public int GetSecondValue(A theA) 
{ 
    return theA.GetSecondInt(); 
} 

发生这种情况:

x = GetFirstValue(a); // x == 1; 
x = GetSecondValue(a); // x == 2; 
x = GetFirstValue(b); // x == 1!! 
x = GetSecondValue(b); // x == 12 
+0

谢谢你这样一个很好的例子。 – user1492518