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
324 views
in Technique[技术] by (71.8m points)

c# - Mystery behind System.Array

We know System.Array is a abstract class and whatever DataType[] we use runtime creates some concrete implementation for us somehow (vague though).

Consider the following snippet.

int[] someInts = { 1, 2, 3, 4 };
IList<int> collection = someInts;
collection.Clear();

collection.Clear() throws NotSupportedException, Nothing surprising there. When I check to see the "StackTrace" am surprised to see it shows some strange "Type" SZArrayHelper at top of the call stack.

StackTrace:

   at System.SZArrayHelper.Clear[T]()//Note this.. How???
   at TestApplication.Program.Main()

How come that is possible? am calling Clear() method on int[] but then how does the call go to SZArrayHelper.Clear. note that Clear is an instance method in SZArrayHelper defined as below.

private void Clear<T>()
{
    throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}

Who creates the instance of "SZArrayHelper" and also note that Clear method is private. Am very confused about what's happening. If at all an instance of "SZArrayHelper" is created and Clear is called then that helper method doing this call should come in the "StackTrace". But that is not the case here.

Can somebody explain what's happening behind the scenes?

Note:

  1. int[] is just an example, you can pretty much simulate it with any type of array, and not only Clear method Add, Contains etc possesses same behavior.

  2. I tried to debug using reflector addin, which gave me the same results. The debugger shows a direct call to SZArrayHelper.Clear<T>().

  3. Google led me to this .NET Arrays, IList, Generic Algorithms, and what about STL?. That helped to understand the kind of magic that is going on behind the scenes, but some mystery still remains.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're not seeing any call to that method, because you're invoking it yourself, as weird as that may sound. SZArrayHelper is a CLR wrapper around an array, that implements the IList<T> interface, kinda like the adapter pattern.

From this perspective, it makes sense that collection.Clear invokes SZArrayHelper.Clear directly.

Hans Passant explains this very well here: https://stackoverflow.com/a/11164210/857807


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

...