简体   繁体   English

什么是C#等效于Java的isInstance()?

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

我知道的is ,并asinstanceof ,但对于反射isInstance()方法?

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

The equivalent of Java's obj.getClass().isInstance(otherObj) in C# is as follows: C#中Java的obj.getClass().isInstance(otherObj)的等价如下:

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. 请注意,虽然Java和C#都处理obj的运行时类型对象(Java java.lang.ClassSystem.Type )(通过.getClass() vs .getType() ),但Java的isInstance将对象作为其参数而C#的IsAssignableFrom需要另一个System.Type对象。

Depends, use is if you don't want to use the result of the cast and use as if you do. 取决于使用的is如果你不想用铸的结果,并使用as如果你这样做。 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;
}

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 :) 我会把它留给别人去测试:)

Below code can be alternative to IsAssignableFrom . 下面的代码可以替代IsAssignableFrom

parentObject.GetType().IsInstanceOfType(inheritedObject)

See Type.IsInstanceOfType description in MSDN. 请参阅MSDN中的Type.IsInstanceOfType描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM