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

C# tương đương isInstance() của Java

Java Class.isInstance() kiểm tra object có gán được cho kiểu không.

Tương đương C#:

  1. Type.IsAssignableFrom()
  2. Toán tử is: bool res = (ob is DemoClass);
  3. Type.IsInstanceOfType(): ob.GetType().IsInstanceOfType(otherOb)

Ví dụ:

object obj = "hello";
bool b1 = obj is string; // true
bool b2 = typeof(string).IsAssignableFrom(obj.GetType()); // true
bool b3 = typeof(string).IsInstanceOfType(obj); // true

Khuyến nghị: Dùng is pattern matching (C# 7+): if (obj is string s) { ... } - vừa kiểm tra vừa cast.