Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตัวดำเนินการ (Operators), ประเภทข้อมูล (Types) และตัวแปร (Variables) ใน C#

ตัวแปร (Variables)

ตัวแปรคือชื่อที่อ้างอิงพื้นที่หน่วยความจำ แต่ละตัวแปรมี Type กำหนดขนาด Layout ช่วงค่า และ Operation ที่ทำได้

ประเภทข้อมูลใน C# (Type System)

แบ่งเป็น 3 หมวดหลัก:

1. Value Types (ประเภทค่า)

  • เก็บค่าโดยตรง (Directly contain data)
  • สืบทอดจาก System.ValueType
  • เก็บใน Stack (โดยทั่วไป)
  • ตัวอย่าง: int, double, bool, char, struct, enum
  • Assignment = Copy ค่า (Deep copy)

2. Reference Types (ประเภทอ้างอิง)

  • เก็บ Reference (Address) ไปยัง Object บน Heap
  • หลายตัวแปรอาจชี้ Object เดียวกัน — เปลี่ยนผ่านตัวหนึ่ง ส่งผลต่ออีกตัว
  • ตัวอย่าง Built-in: object, string, dynamic, delegate, interface, array, class
  • Default value = null

3. Pointer Types (ประเภท Pointer) — Unsafe Context

  • เก็บ Memory Address โดยตรง
  • ใช้ใน unsafe Context เท่านั้น
  • ตัวอย่าง: int* p = &x;
  • ใช้สำหรับ Interop, High-performance, Low-level

ตัวดำเนินการ (Operators)

สัญลักษณ์บอก Compiler ให้ทำ Mathematical/Logical Manipulation

หมวดหมู่หลัก

หมวดตัวดำเนินการตัวอย่าง
Arithmetic+ - * / % ++ --a + b, i++
Relational== != < > <= >=x == y, a > b
Logical&& || ! ^a && b, !flag
Bitwise& | ^ ~ << >>flags & Mask, x << 2
Assignment= += -= *= /= %= &= ^= |= <<= >>=x += 5
Null-related?? ??= ?. ?[]x ?? default, obj?.Prop
Type-relatedis as typeof sizeof nameofobj is string, typeof(int)
Other?: ??= => (lambda) () (cast) newcond ? a : b, x => x*2

Operator Precedence (ลำดับความสำคัญ) — สรุปสำคัญ

  1. Primary: x.y, f(x), a[x], x++, x--, new, typeof, checked, unchecked
  2. Unary: +, -, !, ~, ++x, --x, (T)x, await
  3. Multiplicative: *, /, %
  4. Additive: +, -
  5. Shift: <<, >>
  6. Relational/Type: <, >, <=, >=, is, as
  7. Equality: ==, !=
  8. Bitwise AND: &
  9. Bitwise XOR: ^
  10. Bitwise OR: |
  11. Conditional AND: &&
  12. Conditional OR: ||
  13. Null-coalescing: ??
  14. Conditional: ?:
  15. Assignment: =, +=, -=, ...
  16. Lambda: =>

ตัวอย่างการประกาศตัวแปร

// Value Types
int number = 42;
double price = 19.99;
bool isActive = true;
char grade = 'A';
Point p = new Point(10, 20); // Struct

// Reference Types
string name = "John";
int[] numbers = { 1, 2, 3 };
List items = new List();
object obj = new object();
dynamic dyn = "anything";