【问题标题】:member names cannot be the same as their enclosing type with partial class成员名称不能与其包含部分类的封闭类型相同
【发布时间】:2012-12-12 20:45:53
【问题描述】:

我已经定义了一个具有如下属性的部分类:

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"];

并获取 Fields 字典的内容。但是当我构建时,我得到:

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

为什么?

【问题讨论】:

    标签: c# partial-classes


    【解决方案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; } }
    }
    

    【讨论】:

    • 这就解释了。谢谢!我先看看属性方式。
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 2020-08-24
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2020-07-26
    相关资源
    最近更新 更多