c# - 使用类索引器时如何修复 "member names cannot be the same as their enclosing type"错误?

标签 c# .net indexer

<分区>

我在我的项目中使用了一个名为 Item 的类,我想通过索引器函数在类中获取/设置值。

我创建了索引器函数并得到了主题错误。经过一些研究,问题似乎出在索引器实际上是一个 List.Item,因此是我的错误。我可以将类更改为 Item2 并进行编译,但是这个类被大量使用,如果可能我不想重命名它。这是否可以在不更改我的类(class)名称的情况下解决?还是我只需要忘记这一点并使用函数来获取/设置值而不是索引器?

将抛出此编译时错误的代码示例:

public class Item
{
    public object this[string var_name]
    {
        get { return null; }
        set { }
    }
}

最佳答案

嗯,这是可能的,但您需要为此做一些额外的工作。您需要添加 IndexerName属性:

public class Item
{
    [System.Runtime.CompilerServices.IndexerName("ItemIndexer")]
    public object this[string var_name]
    {
        get { return null; }
        set { }
    }
}

关于c# - 使用类索引器时如何修复 "member names cannot be the same as their enclosing type"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24019458/

相关文章:

c# - 从 C# 休眠计算机

c# - 持久计算列上的 "A dependent property in a ReferentialConstraint is mapped to a store-generated column."(首先是 EntityFramework 数据库)

c# - IComparer 问题

C# 索引器属性问题

C# 在插入时返回标识

c# - 如何以编程方式将 block 添加到 Git 存储库?

c# - 从 List<string> of words 生成最多 X 长度的所有组合

c# - 如何从 WCF 服务应用程序获取客户端地址?

c - Eclipse 索引器不起作用

Ruby 索引器方法