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

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

问题描述

的东西提回答:


  1. 不要担心的方差的,而有问题的产品阵列,而不是 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-会变暗以线性变换,始终是可能的。所以,这个问题特别引起我的注意,因为它已经实施的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.

问:

在我的code,我有以下声明:

In my code, I have following declaration:

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

我的code知道如何使烃源 presents一个数组(在运行时)。我试图让消费code直接访问其索引。但是,如果没有作为IList的,它不能无法做到的。
返回 [对象] 可能需要额外的转换/件,这就是我preventing做。
我可以做的是:

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.

因此​​,我很困惑与

数组的声明,有

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?

推荐答案

阵列不能有索引,因为它需要能够重新present的阵与任何数目的尺寸。为二维阵列的索引器具有比用于一个一维阵列不同的签名。

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.

如果一个索引提供了和一个使用阵列的再presented二维数组会发生什么?

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 然后就可以返回一个 [对象]

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天全站免登陆