开发者

IndexerName attribute on abstract classes

I'm trying to rename my indexer property using IndexerName attribute on my abstract classes. But it still show compilation error The type 'XXX' already contains a definition for 'Item'.

Abstract class:

public abstract class MyAbstract
{
    [IndexerName("Indexer")]
    public abstract string this[string propertyName]
    {
        get;
    }
}

Concrete class:

public class MyConcrete : MyAbstract
{
    string item;

    public string Item
    {
        get { return item; }
        set { item = value; }
    }

    public开发者_如何学C override string this[string propertyName]
    {
        get { return propertyName; }
    }
}

Compilation error:

The type 'MyConcrete' already contains a definition for 'Item'.

I've tried to put IndexerName on indexer override and it show error "Cannot set the IndexerName attribute on an indexer marked override"

How to use IndexerName on abstract classes ?

Thanks in advance.


The issue will be fixed if you just rename the Item to something else, also consider checking this related issue on IndexerName at here and here.


It seems that the compiler checks the naming before applying attributes inheritance. From the declaration of IndexerNameAttribute we can see it can be inherited to derived classes. It makes more sense if the compiler checks the naming after inherited attributes are ready, since attributes can probably affect the names. Maybe there are some reasons that the compiler team decides to check naming first, I don't know. It's not your fault but I think to resolve the issue you need to change the name of the property Item(even I know you are trying not to).

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public sealed class IndexerNameAttribute : Attribute

Another alternative solution is using real methods instead of indexers.

//base abstract class
public abstract string GetItem(string propertyName);
//and implement it in the derived classes
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜