成员名称不能与具有部分类的封闭类型相同

esp*_*var 5 c# partial-classes

我已经使用如下属性定义了一个partial类:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以这样做:

 myItem["key"];
Run Code Online (Sandbox Code Playgroud)

并获取Fields字典的内容.但当我建立我得到:

"成员名称不能与其封闭类型相同"

为什么?

Jon*_*eet 12

索引器自动具有默认名称Item- 这是包含类的名称.就CLR而言,索引器只是一个带参数的属性,并且您不能声明与包含类同名的属性,方法等.

一种选择是重命名您的类,以便不调用它Item.另一种方法是更改​​用于索引器的"属性"名称[IndexerNameAttribute].

破碎的较短例子:

class Item
{
    public int this[int x] { get { return 0; } }
}
Run Code Online (Sandbox Code Playgroud)

修改名称:

class Wibble
{
    public int this[int x] { get { return 0; } }
}
Run Code Online (Sandbox Code Playgroud)

或者按属性:

using System.Runtime.CompilerServices;

class Item
{
    [IndexerName("Bob")]
    public int this[int x] { get { return 0; } }
}
Run Code Online (Sandbox Code Playgroud)