为什么我们需要虚拟方法??? [英] Why do we need VIRTUAL METHODS???

查看:96
本文介绍了为什么我们需要虚拟方法???的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!
我目前是C#编程的新手....
我有一个问题:为什么我们需要虚拟方法? 如果我错了,请纠正我:
虚拟方法是派生类中要重写的方法.由于虚拟方法,基类(派生类的基础部分)可以访问派生类的重写方法和字段. />

 公共  class 基本
 {
     虚拟 公共  void  Go()
        {
           Console.WriteLine(" );
        }
  }

    公共 派生:基础
     {
           公共 覆盖  void  Go()
           {
              Console.WriteLine(" );
           }
     }

/// //...............
 静态  void  Main(字符串 []参数)
{
     派生der =  Derived();

//  ---应用于派生类的基础"部分
[[Base)der).Go(); //  ---输出为派生类" 

}



因此,当我调用基本虚拟方法时,它将在派生类中查找最派生的重写methiod,然后将结果返回给基类方法,从而更改了它的完整实现.....
编译器是否使用任何表(调用的虚拟表)? 如何理解所有这些???

还有一个例子....
当我在表单上创建按钮控件时,我创建了
一个Button类对象...此对象继承了诸如Text,Name等的替代属性...
所以当我分配... button1.Text ="Run button";
因此,override属性将其Text设置为"Run button",然后将其设置为
将此重写的属性在类层次结构中向上"发送到基类...以满足(虚拟公共字符串Text)属性
.....所以呢????它更改了基类成员,但我使用了派生类成员.....
隐藏此属性是否更有效....(通过在派生类中创建一个字段)...我认为这将非常有效,因为它不能被覆盖并且不会将任何新实现发送给基类?
请解释....

解决方案

虚拟方法非常有用,但也可能被滥用.

想象一个具有方法SetText

  public  虚拟  void  SetText(字符串文本)
{
     .text =文本;
}

公共 字符串文本
{
    获取 {返回文本; }
} 

此方法对于基类而言可能就足够了,但是派生类可能更喜欢验证参数或引发事件等.

 公共 事件 EventHandler TextChanged;

受保护的 虚拟 无效 OnTextChanged(EventArgs e)
{
    EventHandler eh = TextChanged;
    如果(嗯!= )
        eh(,e);
}
公共 覆盖  void  SetText(字符串文本)
{
    文字= ValidateText(文字);
    如果(文本!=文本)
    {
        基本 .SetText(text); // 使用基本方法!
        OnTextChanged(EventArgs.Empty);
    }
}
私有 字符串 ValidateText(字符串文本)
{
    字符串 result = // 此处的验证过程
    返回结果;
} 

您可以看到如何使该方法变得更加强大,但又不改变该方法的整体功能.

请注意,我故意将其称为base.SetText.覆盖时,您应该(通常)始终调用基类方法,以确保保留可能属于该方法的任何其他功能.否则,如果稍后更新基类,则可能导致不可预测的结果,并可能导致应用程序中断.


Nick Reshetinsky写道:

由于虚拟方法,基类(派生类的基础部分)可以访问派生类的重写方法和字段.
对于反向关系,这将是正确的... :)

void direved::go()
{
  take_a_smile();
  base::go();
}


实际上,可以重写虚拟方法,但是除非类(或方法)是抽象的,否则不需要.
从技术上讲,您不希望覆盖属性,因为设置/获取值.您应该将覆盖范围限制为方法.


Hi everyone!
I''m currently a novice in C# programming....
I have a question: why do we need the virtual methods???
Please correct me if I''m wrong:
Virtual methods are the methods to be overriden in the derived classes.. Due to virtual methods base classes (base part of a derived class) can have access to the derived class overriden methods and fields.. Like in this example...

 public class Base
 {
     virtual public void Go()
        {
           Console.WriteLine("Base class");
        }
  }

    public class Derived : Base
     {
           public override void Go()
           {
              Console.WriteLine("Derived Class");
           }
     }

/////...............
static void Main(string[] args)
{
     Derived der = new Derived();

// --- applying to the "base" part of derived class
((Base)der).Go();   // --- output is "Derived class"

}



So when I call the base virtual method it looks for the most derived override methiod in the derived classes and then returns the result to the base class method, thus changing the full implementation of it........
Does a compiler use any table (virtual tables of invocations)??
How to understand all that???

And one more example ....
when I create a button control on a form so I create
a Button class object ... this object has inherited overriden properties like Text, Name and etc...
So when I assign... button1.Text = "Run button";
so the override property sets its Text as "Run button" and then it
sends this overriden property "up in the class hierarchy" to the base classes ...to meet the ( virtual public string Text ) property
.....so what???? it changed the base class memeber, but I use the derived class member.....
Is it more effective to hide this property ....(by creating a field in derived class) ...I think it would be much effective, cause it can''t be overriden and doesn''t send any new implementation to the base classes??
Please explain.....

解决方案

Virtual methods are extremely useful but can also be abused.

Imagine a base class that has a method SetText

public virtual void SetText(string text)
{
    this.text = text;
}

public string Text
{
    get { return text; }
}

This method may be enough for the base classes purposes, but a derived class may prefer to validate the parameter or raise an event etc.

public event EventHandler TextChanged;

protected virtual void OnTextChanged(EventArgs e)
{
    EventHandler eh = TextChanged;
    if(eh != null)
        eh(this, e);
}
public override void SetText(string text)
{
    text = ValidateText(text);
    if(Text != text)
    {
        base.SetText(text); // use the base's method!
        OnTextChanged(EventArgs.Empty);
    }
}
private string ValidateText(string text)
{
    string result = null;
    // validation procedure here
    return result;
}

You can see how the method has been made a lot more powerful but without changing the overall function of the method.

Note, I have deliberately called base.SetText. You should (normally) always call the base classes method when overriding to make sure any other functionality that may be part of that method is retained. Not doing so can lead to unpredictable results and possibly breaking of an application if the base class is later updated.


Nick Reshetinsky wrote:

Due to virtual methods base classes (base part of a derived class) can have access to the derived class overriden methods and fields..



It would be true for a reversed relation... :)

void direved::go()
{
  take_a_smile();
  base::go();
}


Actually, virtual methods *can* be overriden, but don''t need to be unless the class (or method) is abstract.

Technically, you don''t want to override properties because the set/get values. You should restrict your overriding to methods.


这篇关于为什么我们需要虚拟方法???的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆