为什么不能在.NET中定义泛型索引器? [英] Why it is not possible to define generic indexers in .NET?

查看:204
本文介绍了为什么不能在.NET中定义泛型索引器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在.NET中创建通用索引器?



以下代码会引发编译器错误:

  public T this< T> [string key] 
{
get {/ *返回泛型类型T. * /}
}

这是否意味着您无法为通用成员集合创建通用索引器?

$

解决方案

我能想到的唯一可以使用的就是这些行: pre> var settings = ConfigurationSection.AppSettings;
var connectionString = settings< string> [connectionString];
var timeout = settings< int> [timeout];

但是这实际上并不会为您购买任何东西。你刚刚用尖括号替换了圆括号(如在(int)设置[timeout]中),但没有获得额外的类型安全,因为你可以自由地做到这一点

  var timeout = settings< int> [connectionString]; 

如果您有强烈但未静态类型的东西,您可能要等到C#4.0 动态关键字。


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"];

But this doesn't actually buy you anything. You've just replaced round parens (as in (int)settings["timeout"]) with angle brackets, but received no additional type safety as you can freely do

var timeout = settings<int>["connectionString"];

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆