简体   繁体   English

IronPython isinstance()的C#等效项

[英]C# Equivalent of IronPython isinstance()

IronPython isinstance(...)的C#等效项是什么?

You should be able to just do: 您应该能够做到:

if (x is Type) {
  ...
}

For example: 例如:

object b = new Button();


if (b is Button) {
   throw new Exception("Button encountered.");
}

If your objective is to really cast the object, you should do it like this: 如果您的目标是真正投射对象,则应该这样进行:

Type typeObject = x as Type;
if(typeObject != null)
{
    ...
}

The first line tries to cast the object "x" and if not succeeded the typeObject will have the null value. 第一行尝试强制转换对象“ x”,如果不成功,则typeObject将具有null值。 This approach is better than the is operator because it will cast the object only once. 此方法比is运算符更好,因为它只会强制转换一次对象。 The is approach tries to cast the object and if succeeded returns true, but typically inside the if you will cast it again like this: is方法会尝试投射对象,如果成功,则返回true,但通常在if内将对象投射为:

if(x is Type)
{
    Type typeObject = (Type)x;
    ...
}

In this code there are actually two casts, one in the is operator, and inside the if. 在这段代码中,实际上有两个强制转换,一个在is运算符中,一个在if内。

Do you mean such thing? 你这个意思吗?

object o = "hello";
if (o is string)
{
    //do something with a string
}

This will check if some object is a string for example. 例如,这将检查某个对象是否为字符串。 If you mean something else please explain better for those not familiar with ironPython. 如果您还有其他意思,请为不熟悉ironPython的用户提供更好的解释。

You could try using reflection. 您可以尝试使用反射。

bool instance = something.GetType().IsInstanceOfType(SomeObject);

As @Shadow Wizard pointed out, you can do the same thing like this: 正如@Shadow向导指出的那样,您可以执行以下操作:

bool isntance = something is SomeObject;

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

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