something to mention for answering:
Don't worry about variance, while the item in question is Array
rather than T[]
.
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…