-->

构件名称不能与它们的封闭类型与局部类(member names cannot be the same

2019-07-05 01:49发布

我已经定义了一个局部类,像这样的属性:

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);
            }
        }
    }
}

这样我可以这样做:

 myItem["key"];

并获得字段字典的内容。 但是,当我建立我得到:

“成员名称不能与它们的封闭类型”

为什么?

Answer 1:

索引自动拥有的默认名称Item -这是你的包含类的名称。 至于CLR而言,索引仅仅是一个参数属性,您不能使用相同的名称包含类声明的属性,方法等。

一种选择是重命名类,所以它不叫Item 。 另一个办法是改变用于索引的“属性”的名称,通过[IndexerNameAttribute]

破碎的较短的例子:

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

按名称变更修正:

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

或属性:

using System.Runtime.CompilerServices;

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


文章来源: member names cannot be the same as their enclosing type with partial class