简体   繁体   English

在派生类上正确实现索引器

[英]Correct implementation of an indexer on a derived class

I have a class, say DerivedBindingList<T> , which is derived from BindingList<T> . 我有一个类,比如DerivedBindingList<T> ,它是从BindingList<T>派生的。

I would like to use an indexer with the derived class, and have coded it as: 我想在派生类中使用索引器,并将其编码为:

        public T this[int index]
        {
            get
            {
                // Getter code
            }
            set
            {
                // Setter code
            }
        }

However, the compiler complains with the following message: "...hides inherited member 'System.Collections.ObjectModel.Collection.this[int]'. Use the new keyword if hiding was intended." 但是,编译器抱怨以下消息:“ ...隐藏继承的成员'System.Collections.ObjectModel.Collection.this [int]'。如果打算隐藏,请使用new关键字。”

I can add the 'new' keyword and the compiler is happy, but should I be doing things differently in some way to avoid this warning? 我可以添加'new'关键字,并且编译器很高兴,但是我应该以某种方式做一些不同的事情以避免这种警告吗?

Perhaps I have to use base.this[] somehow? 也许我必须以某种方式使用base.this []?

Thanks. 谢谢。

The indexer in BindingList isn't virtual, so you can't override it - you'll have to just hide it if you really want to do this. BindingList的索引器不是虚拟的,因此您不能覆盖它-如果您确实想这样做,则只能将其隐藏。

I don't think I'd advise it though - member hiding is a recipe for confusing code. 我认为我不建议这样做-成员隐藏是混淆代码的秘诀。 What are you trying to do? 你想做什么? Do you definitely want to derive from BindingList<T> instead of composing it (ie having a member of your class of type BindingList<T> )? 您是否肯定要从BindingList<T>派生而不是组成它(即,具有BindingList<T>类型的类的成员)? What is your new indexer going to do? 您的新索引器将要做什么?

此警告表明索引器已经存在于基类中,如果要更改其行为,则应覆盖它(如果在基类中定义为虚拟的)或使用new关键字告诉编译器在工作时使用派生的索引器方法带有派生类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM