Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - Why doesn't Array class expose its indexer directly?

something to mention for answering:

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

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

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.


Question:

In my code, I have following declaration:

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

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); 

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

Thus, I'm confused with that:

In the declaration of Array, there is

object IList.this[int index];

So that we can

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

But we cannot

a[0]='a';

except if it was declared as

public object this[int index]; 

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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); 

That will have an indexer.

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); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...