繁体   English   中英

通用类,其参数扩展嵌套类

[英]Generic class whose parameter extends a nested class

这个C#不编译:

public class IdList<T> where T : IdList<T>.Item {
  List<T> List = new List<T>();

  public T this[int id] {
    get => List[id];
    set { }
  }

  public class Item {
    public int id;
    // Not shown: id used for equality and hash.
  }
}

编译器的抱怨是:

类型'IdList'已经包含'Item'的定义

如果我注释掉索引器,它会编译。

我该如何编译? 骑士没有固定。

不合时宜的解决方法不是嵌套Item类。

IDE是MacOS上的Rider 2018.1.4,语言级别7.2。

问题是索引器在编译为.NET字节代码时会变成名为“Item”的属性。 您需要将类型名称更改为其他名称。

解决方案:使用例如System.Runtime.CompilerServices.IndexerName("TheItem")消除名称冲突

public class IdList<T> where T : IdList<T>.Item {
  List<T> List = new List<T>();

  [System.Runtime.CompilerServices.IndexerName("TheItem")]
  public T this[int id] {
    get => List[id];
    set { }
  }

  public class Item {
    public int id;
    // Not shown: id used for equality and hash.
  }
}

编译器错误应该更明确,并且说Item已经被定义为索引器的默认名称(可以被覆盖),IDE应该提供此fixit。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM