Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khác biệt giữa int và Int32 trong C#

Câu trả lời ngắn gọn

Không có khác biệt gì về mặt runtime. int là alias (bí danh) của System.Int32. Chúng compile thành IL giống hệt nhau.

Chi tiết

Đặc điểmintInt32 / System.Int32
Bản chấtC# Keyword (alias).NET Framework Type (struct)
NamespaceKhông cần (global)System (hoặc using System)
Kích thước32-bit signed integer32-bit signed integer
Range-2,147,483,648 đến 2,147,483,647-2,147,483,648 đến 2,147,483,647
IL Typeint32int32
Default value00

Ví dụ minh họa


using System;

class Program 
{
    static void Main() 
    {
        // Cả hai đều OK
        int a = 5;
        Int32 b = 5;           // Cần using System; hoặc System.Int32
        System.Int32 c = 5;    // Fully qualified
        
        Console.WriteLine(a == b);     // True
        Console.WriteLine(a.GetType() == b.GetType()); // True
        Console.WriteLine(typeof(int) == typeof(Int32)); // True
        Console.WriteLine(typeof(int) == typeof(System.Int32)); // True
        
        // Max/Min values
        Console.WriteLine(int.MaxValue);    // 2147483647
        Console.WriteLine(Int32.MaxValue);  // 2147483647
        Console.WriteLine(int.MinValue);    // -2147483648
    }
}

Tất cả C# Aliases vs .NET Types

C# Keyword.NET TypeKích thướcSigned?
sbyteSystem.SByte8-bitYes
byteSystem.Byte8-bitNo
shortSystem.Int1616-bitYes
ushortSystem.UInt1616-bitNo
intSystem.Int3232-bitYes
uintSystem.UInt3232-bitNo
longSystem.Int6464-bitYes
ulongSystem.UInt6464-bitNo
floatSystem.Single32-bitIEEE 754
doubleSystem.Double64-bitIEEE 754
decimalSystem.Decimal128-bitYes
boolSystem.Boolean1-bit (logical)N/A
charSystem.Char16-bitUnicode
stringSystem.StringVariableReference
objectSystem.ObjectReferenceBase type

Khi nào dùng int vs Int32?

Ưu tiên int (C# keyword)

  • Code C# thông thường - idiomatic, readable.
  • Không cần using System;.
  • Team convention thường dùng keyword.

Dùng Int32 / System.Int32 khi

  • Code generation, reflection, serialization libraries.
  • Interop với ngôn ngữ khác (VB.NET, F#) - họ dùng Int32.
  • API công khai cross-language (CLS-compliant).
  • Documentation, spec viết về .NET types.
  • Generic constraints: where T : Int32 (không dùng int).

Lưu ý thú vị


// C# cho phép dùng keyword trong typeof
typeof(int) == typeof(Int32) == typeof(System.Int32) // All true

// Nhưng trong một số context cần type name string
Type.GetType("System.Int32") // OK
Type.GetType("int")          // null - không hiểu keyword

// Serialization/Config thường dùng fully qualified name
// JSON: {"$type": "System.Int32", "$value": 42}

Performance

Zero difference. C# compiler dịch int thành System.Int32 trong metadata. JIT compiler thấy cùng một kiểu.

Best Practice

Quy ước chung: Dùng C# keywords (int, string, bool, object...) trong code logic. Dùng CLR type names (Int32, String, Boolean...) khi làm việc với reflection, serialization, interop, hoặc documentation kỹ thuật.