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

心已入冬 提交于 2019-11-27 11:24:27

问题


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


回答1:


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.




回答2:


bool result = (obj is MyClass); // Better than using 'as'



回答3:


Depends, use is if you don't want to use the result of the cast and use as if you do. You hardly ever want to write:

if(foo is Bar) {
    return (Bar)foo;
}

Instead of:

var bar = foo as Bar;
if(bar != null) {
    return bar;
}



回答4:


just off the top of my head, you could also do:

bool result = ((obj as MyClass) != null)

Not sure which would perform better. I'll leave it up to someone else to benchmark :)




回答5:


Below code can be alternative to IsAssignableFrom.

parentObject.GetType().IsInstanceOfType(inheritedObject)

See Type.IsInstanceOfType description in MSDN.



来源:https://stackoverflow.com/questions/282459/what-is-the-c-sharp-equivalent-to-javas-isinstance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!