开发者

C# Equivalent of IronPython isinstance()

开发者 https://www.devze.com 2023-03-30 22:33 出处:网络
What is 开发者_JAVA百科the C# equivalent of IronPython isinstance(...)?You should be able to just do:

What is 开发者_JAVA百科the C# equivalent of IronPython isinstance(...)?


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消