What is the C# equivalent to Java's isInstance()?

前端 未结 5 940
清歌不尽
清歌不尽 2020-12-13 16:54

I know of is and as for instanceof, but what about the reflective isInstance() method?

5条回答
  •  长情又很酷
    2020-12-13 17:16

    The equivalent of Java’s obj.getClass().isInstance(otherObj) in C# is as follows:

    bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
    

    Note that while both Java and C# work on the runtime type object (Java java.lang.Class ≣ C# System.Type) of an obj (via .getClass() vs .getType()), Java’s isInstance takes an object as its argument, whereas C#’s IsAssignableFrom expects another System.Type object.

提交回复
热议问题