【问题标题】:Item and this[] - Member with the same name is already declared [duplicate]Item 和 this[] - 同名成员已被声明 [重复]
【发布时间】:2011-07-15 21:05:50
【问题描述】:

可能重复:
Class with indexer and property named “Item”

刚刚遇到一些我以前从未见过的东西,想知道为什么会发生这种情况?

对于下面的类,我收到关于“Item”和“this[...]”的编译器错误“已声明具有相同名称的成员”。

public class SomeClass : IDataErrorInfo 
{
    public int Item { get; set; }

    public string this[string propertyName]
    {
        get
        {
            if (propertyName == "Item" && Item <= 0)
            {
                return "Item must be greater than 0";
            }
            return null;
        }
    }

    public string Error
    {
        get { return null; }
    }
}

编译器似乎认为 this[...] 和 Item 使用相同的成员名称。这是正确/正常的吗?我很惊讶我以前没有遇到过这种情况。

【问题讨论】:

标签: c# .net compiler-errors indexer


【解决方案1】:

当你像这样定义索引器时:

this[string propertyName]

编译成.Item属性。

您可以使用索引器的[System.Runtime.CompilerServices.IndexerName("NEW NAME FOR YOUR PROPERTY")] 属性来解决此问题。

【讨论】:

    【解决方案2】:

    是的。 this[] 编译为一个名为 Item 的属性默认情况下。您可以使用 System.Runtime.CompilerServices.IndexerName 属性更改它。 (MSDN link)

    【讨论】:

      【解决方案3】:

      这很正常。 C# 语言有关键字“this”,用于声明索引器,但在编译后的类中,索引器的 get 方法将称为“get_Item”(这是 .NET 中的跨语言约定)。由于编译器希望为您的 Item 属性的 getter 赋予相同的名称,因此会报告错误。

      【讨论】:

        【解决方案4】:

        如果你用 IL 代码查看 IDataErrorInfo 接口,你会发现

        .class public interface abstract auto ansi IDataErrorInfo
        {
            .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = { string('Item') }
            .property instance string Error
            {
                .get instance string System.ComponentModel.IDataErrorInfo::get_Error()
            }
        
            .property instance string Item
            {
                .get instance string System.ComponentModel.IDataErrorInfo::get_Item(string)
            }
        
        }
        

        在 C# 中确实可以翻译成

        public interface IDataErrorInfo
        {
            // Properties
            string Error { get; }
            string this[string columnName] { get; }
        }
        

        所以原因是 C# 确实在 this 语法后面隐藏了一些特殊的方法名称,这确实与 CLR 使用的真实方法名称发生冲突。

        【讨论】:

          猜你喜欢
          • 2014-02-08
          • 1970-01-01
          • 2017-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-12
          • 2017-08-04
          • 1970-01-01
          相关资源
          最近更新 更多