【问题标题】:why virtual methods [duplicate]为什么虚拟方法[重复]
【发布时间】:2012-09-23 00:30:13
【问题描述】:

可能重复:
What are Virtual Methods?

在 C# 中,即使您没有将基类方法声明为虚拟方法,编译器也会在方法签名匹配时调用最新的派生类方法。 如果没有 virtual 关键字,我们只会收到警告消息,说明将调用派生方法(现在可以使用 new 关键字删除)。

当没有 this 关键字时,将方法声明为虚拟的有什么用处,并且签名匹配时调用最后一个派生类中的方法。

我不明白这里的一些东西。 “虚拟”是为了代码可读性目的吗? 史密斯

【问题讨论】:

标签: c#


【解决方案1】:

这并不是真正的“最新派生方法”。这是关于当你使用多态性时会发生什么。当您在期望父类的上下文中使用派生类的实例时,如果您不使用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

【讨论】:

  • 谢谢你提供了这么好的例子。
【解决方案2】:

可以重新定义虚拟方法。在 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 

【讨论】:

  • 我了解“虚拟”方法的工作原理。我的观点是没有这个关键字,除了一条警告消息外,行为是相同的。换句话说,我可以在不使用关键字的情况下获得“虚拟”方法实现的全部好处。使用这个关键字是更好的做法吗?
  • 不,事情的运作方式完全不同。 virtual 不是语法糖。请阅读我的回复。
  • @user1492518 看看这个例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 2011-02-08
  • 1970-01-01
相关资源
最近更新 更多