Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用索引器和名为“的属性初始化”;项目「;_C#_.net_Indexer - Fatal编程技术网

C# 使用索引器和名为“的属性初始化”;项目「;

C# 使用索引器和名为“的属性初始化”;项目「;,c#,.net,indexer,C#,.net,Indexer,是否可以在.NET 4中创建具有以下内容的类: 索引器 名为“Item”的属性 例如,这个C#类不会为我编译: public class MyClass { public object Item { get; set; } public object this[string index] { get { return null; } set { } } } 编译器给出了一个错误: 类型“MyClass”已包含“Item”的定义 虽然我只显式定义了项一次。如果我没记错的话,这样的

是否可以在.NET 4中创建具有以下内容的类:

  • 索引器
  • 名为“Item”的属性
  • 例如,这个C#类不会为我编译:

    public class MyClass
    {
        public object Item { get; set; }
        public object this[string index] { get { return null; } set { } }
    }
    
    编译器给出了一个错误:

    类型“MyClass”已包含“Item”的定义


    虽然我只显式定义了
    一次。

    如果我没记错的话,这样的索引器可以通过“Item()”方法从VB.Net访问。这就是“定义两次”的来源。

    基于,可以使用属性重命名索引器

    public class MyClass
    {
        public object Item { get; set; }
        [System.Runtime.CompilerServices.IndexerName("MyItem")]
        public object this[string index] { get { return null; } set { } }
    }
    
    C#在内部为不支持索引器的语言创建一个名为
    Item
    的属性。您可以使用控制此名称,如下所示:

    [IndexerName("MyIndexer")]
    public object this[string index]
    {
        get { return blah; }
    }