سؤال

After looking at the source code for Int32 while doing some research as to why my DataContractSerializer would not serialize my struct but when using int it works fine, I came across a curious bit of code

public struct Int32 : ...
{
   internal int m_value;

   public const int MaxValue = 0x7fffffff;

If Int32 and int are aliases why on earth is int declared inside Int32?

هل كانت مفيدة؟

المحلول

int vs. Int32 is irrelevant to this issue. That the field is displayed as int is just because the tool you use to look at it replaces those types by their aliases when it displays them. If you look at is with a lower level tool you'll see that it doesn't know about int, only about Int32.

The problem is that the Int32 struct contains an Int32 field.

"What is the int standing on?" "You're very clever, young man, very clever," said the old lady. "But it's ints all the way down!"

The solution to this problem is magic. The runtime knows what an Int32 is and gives it special treatment avoiding infinite recursion. You can't write a custom struct that contains itself as a field. Int32 is a built in type, no normal struct. It just appears as struct for consistency's sake.

نصائح أخرى

well its almost the same as alias what this will do will put the int everywhere where int32 is used because MaxValue is constant it will not be created with the value.

so basically creating int32 will create one element structure with only int. but thanks to using structure MaxValue can be obtain at any moment.

This question is not as silly as it seems, because normally it would lead to a cyclic struct layout to have an instance field inside the struct which had the same type as the entire struct. For example, this will not work, cleraly:

struct MyStruct
{
  internal MyStruct m_value;
}

Gives:

error CS0523: Struct member 'SomeNamespace.MyStruct.m_value' of type 'SomeNamespace.MyStruct' causes a cycle in the struct layout

compile-time error. So there must be some magic for Int32.

Update: See thread If Int32 is just an alias for int, how can the Int32 class use an int?.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top