在哪里使用方法覆盖 [英] where to use Method overiding

查看:88
本文介绍了在哪里使用方法覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道我们可以在哪里以及如何使用方法覆盖.任何人都可以举一个方法重载的重要例子..我的意思是在什么情况下我们必须使用重载??/

谢谢
Rakesh

anyone know how and where we can use the method overriding. can anyone give critical example of method overriding.. i mean in what situation we have to use the overriding ??/

Thanks
Rakesh

推荐答案

要使用同一方法调用添加其他功能或其他功能时.一个很好的例子是ToString().当您可以在列表框(或其他列表容器)中显示要显示的对象的集合时,可以简单地重写Object.ToString()方法以返回所需的文本,如下所示:

When you want to add different or additional functionality with the same method call. A good example would be ToString(). When you can a collection of objects that you want to display in a listbox (or other list container), you can simply override the Object.ToString() method to return the desired text, like so:

public class MyObject
{
    public string DisplayName { get; set; }

    public MyObject(string name)
    {
        DisplayName = name;
    }

    public override string ToString()
    {
        return DisplayName;
    }
}


用法:


Usage:

List<MyObject> myObjects = new List<MyObject>;

// populate the collection, and then do this:
listbox1.Items.AddRange(MyObjects.ToArray());


由于列表框中的Items集合是一个对象(而不是字符串),它将调用该对象的ToString方法来获取显示的文本.通常,ToString将返回对象的类名(在上面的示例中,该类名将为"MyObject".但是,通过覆盖ToString(),列表框将改为显示DisplayName属性的内容.


Since the Items collection in the listbox is an object (as opposed to a string), it will call the object''s ToString method to get displayed text. Normally, ToString would return the class name of the object (in the example shown above, that would have been "MyObject". However, by overriding ToString(), the listbox will show the contents of the DisplayName property instead.


这篇关于在哪里使用方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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