member names cannot be the same as their enclosing type with partial class

允我心安 提交于 2019-12-19 22:01:42

问题


I have defined a partial class with a property like this:

public partial class Item{    
    public string this[string key]
    {
        get
        {
            if (Fields == null) return null;
            if (!Fields.ContainsKey(key))
            {
                var prop = GetType().GetProperty(key);

                if (prop == null) return null;

                return prop.GetValue(this, null) as string;
            }

            object value = Fields[key];

            return value as string;
        }
        set
        {
            var property = GetType().GetProperty(key);
            if (property == null)
            {
                Fields[key] = value;
            }
            else
            {
                property.SetValue(this, value, null);
            }
        }
    }
}

So that i can do:

 myItem["key"];

and get the content of the Fields dictionary. But when i build i get:

"member names cannot be the same as their enclosing type"

Why?


回答1:


Indexers automatically have a default name of Item - which is the name of your containing class. As far as the CLR is concerned, an indexer is just a property with parameters, and you can't declare a property, method etc with the same name as the containing class.

One option is to rename your class so it's not called Item. Another would be to change the name of the "property" used for the indexer, via [IndexerNameAttribute].

Shorter example of brokenness:

class Item
{
    public int this[int x] { get { return 0; } }
}

Fixed by change of name:

class Wibble
{
    public int this[int x] { get { return 0; } }
}

Or by attribute:

using System.Runtime.CompilerServices;

class Item
{
    [IndexerName("Bob")]
    public int this[int x] { get { return 0; } }
}


来源:https://stackoverflow.com/questions/13848287/member-names-cannot-be-the-same-as-their-enclosing-type-with-partial-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!