Is a static member movable or fixed anyway?
In another topic, a nice guy told me by quote Eric Lippert's words:The significance of static has to do with the knowledge and certainties the compiler has at compile time of a certain class/struct/field what have you. It has nothing to do with memory locations and them being fixed or not, etc.
But I'm still not so sure, because the compiler allows something shown below happen.
struct MyStruct
{
public static int[] Arr = {1,3,5};
}
static void Test<T>(ref T t) where T:struct
{
Console.WriteLine (t);
}
void Main()
{
Test(ref MyStruct.Arr[2]);//output: as expected 5
}
Are the ref arguments totally different things compare to the c++ references, or a behind the scene pin happens every time some args are passed by ref? If the static members are movable, how does the runtime guarantee the address of an array element won't change during the execution of the called function? I've learned from an experiment that the return values of objects' Item prop other than arrays' are not allowed to be passed byRef. I thought that's because array elements are allocated in a chunk of continuous memory, but if the whole array is movable, how can one take an address of its elements?
I'm kinda stuck by this uncertainty. I'd very much appreciate it if someone could give some certain answer. Thanks in advance!
~~~~~~~~~~~~~~~~开发者_Go百科~~
Trying to understand it:
So, any managed operation as long as the compiler allows it happen, We shouldn't sweat it, right? I have some C/C++ background, I think I understand the meaning of "static" pretty well for c++, only the movability thing of managed code make me dubious. Any managed object, no matter it's on a stack or managed heap, A ref arg can always point to it correctly, right?
C# ref arguments aren't totally different from C++ references, but they are different in this respect.
C# ref arguments are known to the garbage collector and it will adjust them if it promotes objects to a different generation.
C++ references are invisible to the .NET garbage collector, they will break if the target is not pinned and the garbage collector runs.
(C++/CLI supports both .NET references and native references)
If the static members are movable, how does the runtime guarantee the address of a array element won't change during the execution of the called function?
It doesn't. But the function will use the updated address, because it's .NET code also.
And none of this changes depending on whether there's a static field referring to the array. (In fact the array itself isn't static, only the field referring to it. This fact makes the whole question nonsensical.)
精彩评论