简体   繁体   中英

Correct implementation of an indexer on a derived class

I have a class, say DerivedBindingList<T> , which is derived from 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."

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?

Perhaps I have to use base.this[] somehow?

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.

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> )? What is your new indexer going to do?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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