为什么不能在 .NET 中定义通用索引器? [英] Why it is not possible to define generic indexers in .NET?
问题描述
为什么不能在 .NET 中创建通用索引器?
Why can't you create a generic indexer in .NET?
以下代码引发编译器错误:
the following code throws a compiler error:
public T this<T>[string key]
{
get { /* Return generic type T. */ }
}
这是否意味着您不能为通用成员集合创建通用索引器?
Does this mean you can't create a generic indexer for a generic member collection?
推荐答案
我能想到的唯一可以使用的东西是这样的:
The only thing I can think of this can be used is something along these lines:
var settings = ConfigurationSection.AppSettings;
var connectionString = settings<string>["connectionString"];
var timeout = settings<int>["timeout"];
但这实际上并没有给你买任何东西.您刚刚用尖括号替换了圆括号(如 (int)settings["timeout"]
中的那样),但没有像您可以自由做的那样获得额外的类型安全
But this doesn't actually buy you anything. You've just replaced round parentheses (as in (int)settings["timeout"]
) with angle brackets, but received no additional type safety as you can freely do
var timeout = settings<int>["connectionString"];
如果你有一些强类型但不是静态类型的东西,你可能想等到 C# 4.0 和它的 dynamic 关键字.
If you have something that's strongly but not statically typed, you might want to wait until C# 4.0 with its dynamic keyword.
这篇关于为什么不能在 .NET 中定义通用索引器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!