与 Java 的 isInstance() 等效的 C# 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/282459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the C# equivalent to Java's isInstance()?
提问by diegogs
I know of is
and as
for instanceof
, but what about the reflective isInstance()method?
我知道is
and as
for instanceof
,但是反射isInstance()方法呢?
采纳答案by Konrad Rudolph
The equivalent of Java's obj.getClass().isInstance(otherObj)
in C# is as follows:
obj.getClass().isInstance(otherObj)
C#中Java的等价物如下:
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# 都在(via vs )的运行时类型对象 (Java java.lang.Class
? C# System.Type
) 上工作,但 Java将一个对象作为其参数,而 C#需要另一个对象。obj
.getClass()
.getType()
isInstance
IsAssignableFrom
System.Type
回答by CodingWithSpike
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 :)
不确定哪个表现更好。我会把它留给其他人来进行基准测试:)
回答by Ana Betts
bool result = (obj is MyClass); // Better than using 'as'
回答by Ana Betts
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:
视情况而定,is
如果您不想使用演员表的结果,请使用,如果您想使用,请使用as
。你几乎不想写:
if(foo is Bar) {
return (Bar)foo;
}
Instead of:
代替:
var bar = foo as Bar;
if(bar != null) {
return bar;
}
回答by Youngjae
Below code can be alternative to IsAssignableFrom
.
下面的代码可以替代IsAssignableFrom
.
parentObject.GetType().IsInstanceOfType(inheritedObject)
See Type.IsInstanceOfTypedescription in MSDN.
请参阅MSDN 中的Type.IsInstanceOfType描述。