In C# what is the equivalent of “is” keyword but using Type objects

旧巷老猫 提交于 2019-11-30 22:39:17

It depends on what you need; IsAssignableFrom, perhaps:

bool stringIsObj = typeof(object).IsAssignableFrom(typeof(string));

or IsSubclassOf:

bool stringIsObj = typeof(string).IsSubclassOf(typeof(object));

typeof(ParentClass).IsAssignableFrom(typeof(ChildClass))

I suggest you search for an equivalent. Instead of using the "is" keyword like this:

if (object is class)
{ ... }

you could simply compare the types of those two like this:

if( typeof(object) == typeof(class)
{ ... }

BUT: this is not the same, the "is" keyword can determine if the object-class is of the specified class, an inheritence of that class, implements the interface, etc, whereas the typeof() equivalence just compares the actual type.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!