为什么 Array 类不直接公开其索引器? [英] Why doesn't Array class expose its indexer directly?

查看:27
本文介绍了为什么 Array 类不直接公开其索引器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要回答的问题:

  1. 不要担心方差,虽然有问题的项目是Array而不是T[].

  1. Don't worry about variance, while the item in question is Array rather than T[].

多维数组的类似案例是 [此处]

A similar case for multi-dimension arrays is [here]

也就是说,N-dims 到线性变换,总是可能的.所以这个问题特别引起了我的注意,因为它已经为线性索引器实现了 IList.

That is, N-dims to linear transform, is always possible. So this question especially caught my attention, since it already implemented IList for a linear indexer.

问题:

在我的代码中,我有以下声明:

In my code, I have following declaration:

public static Array ToArray<T>(this T source); 

我的代码知道如何让 souce 呈现一个数组(在运行时).我试图让消费代码直接访问其索引器.但是如果没有as IList",就不能做到.返回 object[] 可能需要额外的转换/转换,这就是我要阻止的.我能做的是:

My code knows how to make souce presents an array(at runtime). And I'm trying to allow the consuming code to access its indexer directly. But without "as IList", it cannot not be done. To return object[] might require extra converting/casting, that's what I'm preventing to do. What I can do is:

public static IList ToArray<T>(this T source); 

但我认为名为 ToArray 的方法返回一个 IList 看起来很奇怪.

But I would think that a method named ToArray returns an IList looked strange.

因此,我对此感到困惑:

Thus, I'm confused with that:

Array的声明中,有

object IList.this[int index];

这样我们就可以

Array a;
a=Array.CreateInstance(typeof(char), 1);
(a as IList)[0]='a';

但我们不能

a[0]='a';

除非它被声明为

public object this[int index]; 

我能看到的唯一区别是它要求我们通过实现它的接口 IList 显式使用它的索引器,但为什么呢?有好处吗?还是有暴露的问题?

The only difference I can see is that it requires we use its indexer explicitly through the interface IList by which it was implemented, but why? Are there benefits? Or are there exposing issues?

推荐答案

Array 不能有索引器,因为它需要能够表示具有任意维数的数组.二维数组的索引器与一维数组的索引器具有不同的签名.

Array can't have an indexer because it needs to be able to represent an array with any number of dimensions. The indexer for a two dimensional array has a different signature than for a one dimensional array.

如果在表示二维数组的 Array 上提供并使用索引器,会发生什么?

If an indexer was provided and used on an Array that represented a two dimensional array what should happen?

语言设计者选择的解决方案是根本不包含索引器.

The solution that the language designers choose was to just not include an indexer at all.

如果您知道您的 ToArray 方法将始终返回一维数组,请考虑使用:

If you know that your ToArray method will always return a one dimensional array then consider using:

public static T[] ToArray<T>(this T source); 

那将有一个索引器.

如果数组中的元素不都是 T 类型,那么你可以返回一个 object[]:

If the elements in the array will not all be of type T then you can return an object[]:

public static object[] ToArray<T>(this T source); 

这篇关于为什么 Array 类不直接公开其索引器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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