简体   繁体   中英

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. This approach is better than the is operator because it will cast the object only once. 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:

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.

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.

You could try using reflection.

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

As @Shadow Wizard pointed out, you can do the same thing like this:

bool isntance = something is SomeObject;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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