开发者

"is" - operator for Type

开发者 https://www.devze.com 2023-04-05 12:44 出处:网络
I use the \"is\" operator to find a certain class: for(int i=0; i<screens.Count; i++){ if(screen is ScreenBase){

I use the "is" operator to find a certain class:

for(int i=0; i<screens.Count; i++){
  if(screen is ScreenBase){
    //do something...
  }
}

This works fine especially as it finds any class that inherits from the ScreenBase but not the base classes from ScreenBase.

I would like to do the same when I know only the Type and don't want to instantiate the class:

Type screenType = GetType(line);
if (screenType is ScreenBase)

But this comparsion produces a warning as 开发者_如何学Goit will compare to the "Type" class.

The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?


The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?

If GetType(line) returns a type (I'd recommend a better name for that, btw), you can use Type.IsAssignableFrom:

if (typeof(ScreenBase).IsAssignableFrom(GetType(line)))
{
}


If you want to know specifically if it derives from the type, use Type.IsSubclassOf(). This will not work for interfaces.

Type screenType = GetType(line);
if (screenType.IsSubclassOf(typeof(ScreenBase)))
{
    // do stuff...
}

Otherwise if you want to know if the type could be assigned to a variable of a certain type, use Type.IsAssignableFrom(). This will work for interfaces.

Type screenType = GetType(line);
if (typeof(ScreenBase).IsAssignableFrom(screenType)) // note the usage is reversed
{
    // do stuff...
}

Do note that you don't necessarily need a type object to determine this, you can do this with an instance of the object using Type.IsInstanceOfType(). It will behave more or less like IsAssignableFrom().

if (typeof(ScreenBase).IsInstanceOfType(line)) // note the usage is reversed
{
    // do stuff...
}


you are looking for Type.IsAssignableFrom

0

精彩评论

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

关注公众号