泛型 class 其参数扩展嵌套 class
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.
}
}
编译器的投诉是:
The type 'IdList' already contains a definition for 'Item'
如果我注释掉索引器,它会编译。
我怎样才能让它编译? Rider 没有固定装置。
不时尚的解决方法是不嵌套项目 class。
IDE 是 Rider 2018.1.4,语言级别 7.2,在 macOS 上。
问题是索引器在编译为 .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 应该提供此修复。
此 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.
}
}
编译器的投诉是:
The type 'IdList' already contains a definition for 'Item'
如果我注释掉索引器,它会编译。
我怎样才能让它编译? Rider 没有固定装置。
不时尚的解决方法是不嵌套项目 class。
IDE 是 Rider 2018.1.4,语言级别 7.2,在 macOS 上。
问题是索引器在编译为 .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 应该提供此修复。