Тип данных System.Int32 - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день. Пытаюсь разобраться с типами данных (для примера выбрала System.Int32). На referencesousre показано как реализован System.Int32 (код приложу ниже), но кое-что мне в этом коде непонятно. Например, если записать
Листинг программы
  1. int x = 15;
, то фактически происходит инициализация переменной x типа System.Int32. Заглядываю в описание типа System.Int32 и в 38 строке вижу объявление переменной m_value типа int, которая (если я правильно понимаю) и будет равна 15. Отсюда возникают вопросы: 1. Почему в структуре Int32 объявляется переменная типа int? Разве int и System.Int32 не равнозначны? Получается, что внутри структуры Int32 объявлена структура Int32? 2. Как в переменную m_value попадает значение 15? 3. Где же тогда посмотреть как устроен тип данных intи, в частности, присваивание значения переменной?
Листинг программы
  1. // ==++==
  2. //
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. //
  5. // ==--==
  6. /*============================================================
  7. **
  8. ** Class: Int32
  9. **
  10. **
  11. ** Purpose: A representation of a 32 bit 2's complement
  12. ** integer.
  13. **
  14. **
  15. ===========================================================*/
  16. namespace System {
  17. using System;
  18. using System.Globalization;
  19. ///#if GENERICS_WORK
  20. /// using System.Numerics;
  21. ///#endif
  22. using System.Runtime;
  23. using System.Runtime.InteropServices;
  24. using System.Diagnostics.Contracts;
  25. [Serializable]
  26. [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
  27. [System.Runtime.InteropServices.ComVisible(true)]
  28. #if GENERICS_WORK
  29. public struct Int32 : IComparable, IFormattable, IConvertible
  30. , IComparable<Int32>, IEquatable<Int32>
  31. /// , IArithmetic<Int32>
  32. #else
  33. public struct Int32 : IComparable, IFormattable, IConvertible
  34. #endif
  35. {
  36. internal int m_value;
  37. public const int MaxValue = 0x7fffffff;
  38. public const int MinValue = unchecked((int)0x80000000);
  39. // Compares this object to another object, returning an integer that
  40. // indicates the relationship.
  41. // Returns a value less than zero if this object
  42. // null is considered to be less than any instance.
  43. // If object is not of type Int32, this method throws an ArgumentException.
  44. //
  45. public int CompareTo(Object value) {
  46. if (value == null) {
  47. return 1;
  48. }
  49. if (value is Int32) {
  50. // Need to use compare because subtraction will wrap
  51. // to positive for very large neg numbers, etc.
  52. int i = (int)value;
  53. if (m_value < i) return -1;
  54. if (m_value > i) return 1;
  55. return 0;
  56. }
  57. throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt32"));
  58. }
  59. public int CompareTo(int value) {
  60. // Need to use compare because subtraction will wrap
  61. // to positive for very large neg numbers, etc.
  62. if (m_value < value) return -1;
  63. if (m_value > value) return 1;
  64. return 0;
  65. }
  66. public override bool Equals(Object obj) {
  67. if (!(obj is Int32)) {
  68. return false;
  69. }
  70. return m_value == ((Int32)obj).m_value;
  71. }
  72. [System.Runtime.Versioning.NonVersionable]
  73. public bool Equals(Int32 obj)
  74. {
  75. return m_value == obj;
  76. }
  77. // The absolute value of the int contained.
  78. public override int GetHashCode() {
  79. return m_value;
  80. }
  81. [System.Security.SecuritySafeCritical] // auto-generated
  82. [Pure]
  83. public override String ToString() {
  84. Contract.Ensures(Contract.Result<String>() != null);
  85. return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
  86. }
  87. [System.Security.SecuritySafeCritical] // auto-generated
  88. [Pure]
  89. public String ToString(String format) {
  90. Contract.Ensures(Contract.Result<String>() != null);
  91. return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
  92. }
  93. [System.Security.SecuritySafeCritical] // auto-generated
  94. [Pure]
  95. public String ToString(IFormatProvider provider) {
  96. Contract.Ensures(Contract.Result<String>() != null);
  97. return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
  98. }
  99. [Pure]
  100. [System.Security.SecuritySafeCritical] // auto-generated
  101. public String ToString(String format, IFormatProvider provider) {
  102. Contract.Ensures(Contract.Result<String>() != null);
  103. return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
  104. }
  105. [Pure]
  106. public static int Parse(String s) {
  107. return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
  108. }
  109. [Pure]
  110. public static int Parse(String s, NumberStyles style) {
  111. NumberFormatInfo.ValidateParseStyleInteger(style);
  112. return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
  113. }
  114. // Parses an integer from a String in the given style. If
  115. // a NumberFormatInfo isn't specified, the current culture's
  116. // NumberFormatInfo is assumed.
  117. //
  118. [Pure]
  119. public static int Parse(String s, IFormatProvider provider) {
  120. return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
  121. }
  122. // Parses an integer from a String in the given style. If
  123. // a NumberFormatInfo isn't specified, the current culture's
  124. // NumberFormatInfo is assumed.
  125. //
  126. [Pure]
  127. public static int Parse(String s, NumberStyles style, IFormatProvider provider) {
  128. NumberFormatInfo.ValidateParseStyleInteger(style);
  129. return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
  130. }
  131. // Parses an integer from a String. Returns false rather
  132. // than throwing exceptin if input is invalid
  133. //
  134. [Pure]
  135. public static bool TryParse(String s, out Int32 result) {
  136. return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
  137. }
  138. // Parses an integer from a String in the given style. Returns false rather
  139. // than throwing exceptin if input is invalid
  140. //
  141. [Pure]
  142. public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) {
  143. NumberFormatInfo.ValidateParseStyleInteger(style);
  144. return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
  145. }
  146. //
  147. // IConvertible implementation
  148. //
  149. [Pure]
  150. public TypeCode GetTypeCode() {
  151. return TypeCode.Int32;
  152. }
  153. /// <internalonly/>
  154. bool IConvertible.ToBoolean(IFormatProvider provider) {
  155. return Convert.ToBoolean(m_value);
  156. }
  157. /// <internalonly/>
  158. char IConvertible.ToChar(IFormatProvider provider) {
  159. return Convert.ToChar(m_value);
  160. }
  161. /// <internalonly/>
  162. sbyte IConvertible.ToSByte(IFormatProvider provider) {
  163. return Convert.ToSByte(m_value);
  164. }
  165. /// <internalonly/>
  166. byte IConvertible.ToByte(IFormatProvider provider) {
  167. return Convert.ToByte(m_value);
  168. }
  169. /// <internalonly/>
  170. short IConvertible.ToInt16(IFormatProvider provider) {
  171. return Convert.ToInt16(m_value);
  172. }
  173. /// <internalonly/>
  174. ushort IConvertible.ToUInt16(IFormatProvider provider) {
  175. return Convert.ToUInt16(m_value);
  176. }
  177. /// <internalonly/>
  178. int IConvertible.ToInt32(IFormatProvider provider) {
  179. return m_value;
  180. }
  181. /// <internalonly/>
  182. uint IConvertible.ToUInt32(IFormatProvider provider) {
  183. return Convert.ToUInt32(m_value);
  184. }
  185. /// <internalonly/>
  186. long IConvertible.ToInt64(IFormatProvider provider) {
  187. return Convert.ToInt64(m_value);
  188. }
  189. /// <internalonly/>
  190. ulong IConvertible.ToUInt64(IFormatProvider provider) {
  191. return Convert.ToUInt64(m_value);
  192. }
  193. /// <internalonly/>
  194. float IConvertible.ToSingle(IFormatProvider provider) {
  195. return Convert.ToSingle(m_value);
  196. }
  197. /// <internalonly/>
  198. double IConvertible.ToDouble(IFormatProvider provider) {
  199. return Convert.ToDouble(m_value);
  200. }
  201. /// <internalonly/>
  202. Decimal IConvertible.ToDecimal(IFormatProvider provider) {
  203. return Convert.ToDecimal(m_value);
  204. }
  205. /// <internalonly/>
  206. DateTime IConvertible.ToDateTime(IFormatProvider provider) {
  207. throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime"));
  208. }
  209. /// <internalonly/>
  210. Object IConvertible.ToType(Type type, IFormatProvider provider) {
  211. return Convert.DefaultToType((IConvertible)this, type, provider);
  212. }
  213. }
  214. }

Решение задачи: «Тип данных System.Int32»

textual
Листинг программы
  1. public struct Int32 : IComparable, IFormattable, IConvertible
  2.     {
  3.         internal Int32 m_value;
  4.        ...
  5.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

7   голосов , оценка 3.286 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы