成员名称不能与它们的封闭类型与局部类 [英] member names cannot be the same as their enclosing type with partial class

查看:207
本文介绍了成员名称不能与它们的封闭类型与局部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

为什么?

推荐答案

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

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.

一种选择是重命名类,所以它不叫项目。另一个办法是更改用于索引的财产的名义,通过 [IndexerNameAttribute]

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].

破碎短的例子:

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

或者

using System.Runtime.CompilerServices;

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

这篇关于成员名称不能与它们的封闭类型与局部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆