To check if a type is a subclass of another type in C#, it's easy:

typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true

However, this will fail:

typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false

Is there any way to check whether a type is either a subclass OR of the base class itself, without using an OR operator or using an extension method?

Apparently, no.

Here's the options:

Type.IsSubclassOf

As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:

void Main()
{
typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
typeof(Base).IsSubclassOf(typeof(Base)).Dump();
} public class Base { }
public class Derived : Base { }

Output:

True
False

Which indicates that Derived is a subclass of Base, but that Baseis (obviously) not a subclass of itself.

Type.IsAssignableFrom

Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True for the two above questions, it will also return True for these, which you probably don't want:

void Main()
{
typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
} public class Base { }
public class Derived : Base { }

Here you get the following output:

True
True
True

The last True there would indicate, if the method only answered the question asked, that uint[]inherits from int[] or that they're the same type, which clearly is not the case.

So IsAssignableFrom is not entirely correct either.

is and as

The "problem" with is and as in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type objects.

In other words, this won't compile:

SubClass is BaseClass
^--+---^
|
+-- need object reference here

nor will this:

typeof(SubClass) is typeof(BaseClass)
^-------+-------^
|
+-- need type name here, not Type object

nor will this:

typeof(SubClass) is BaseClass
^------+-------^
|
+-- this returns a Type object, And "System.Type" does not
inherit from BaseClass

Conclusion

While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

which of course makes more sense in a method:

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase)
|| potentialDescendant == potentialBase;
}

How do I check if a type is a subtype OR the type of an object?的更多相关文章

  1. Check类之duplicate declaration checking/Class name generation/Type Checking

    1.duplicate declaration checking /** Check that variable does not hide variable with same name in * ...

  2. 训练caffe:registry.count(type) == 0 (1 vs. 0) Solver type Nesterov already registered

    命令:./continue-train.sh 内容:../../caffe-master/build/tools/caffe train -gpu=$1 -solver=solver.prototxt ...

  3. Format specifies type 'int' but the argument has type 'struct node *'

    /Users/Rubert/IOS/iworkspace/LineList/LineList/main.c::: Format specifies type 'int' but the argumen ...

  4. 前台传参数时间类型不匹配:type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'

    springMVC action接收参数: org.springframework.validation.BindException: org.springframework.validation.B ...

  5. Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx': no matching editors or conversion strategy found

    今天在完成项目的时候遇到了下面的异常信息: 04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.cor ...

  6. type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object

    今天在进行代码检查的时候出现下面的异常: type parameters of <T>T cannot be determined; no unique maximal instance ...

  7. Spring 整合 Flex (BlazeDS)无法从as对象 到 Java对象转换的异常:org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.Date' to required type 'java.sql.Timestamp' for property 'wfsj'; nested exception is java.lang.Ill

    异常信息如下: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value ...

  8. 解决BeanNotOfRequiredTypeException: Bean named 'XXX' must be of type XXX, but was actually of type XXX问题

    Java新手,困扰了一下午. 发布时总是报这样一个错误. org.springframework.beans.factory.BeanCreationException: Error creating ...

  9. spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endtime'

    在使用spring mvc中,绑定页面传递时间字符串数据给Date类型是出错: Failed to convert property value of type [java.lang.String] ...

随机推荐

  1. 代码中修改组件的margin属性

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_ ...

  2. Java Hotspot G1 GC的一些关键技术

    G1 GC,全称Garbage-First Garbage Collector,通过-XX:+UseG1GC参数来启用,作为体验版随着JDK 6u14版本面世,在JDK 7u4版本发行时被正式推出,相 ...

  3. SQLServer 脚本测试

    最近在做大数据同步的工作.很少数据需要特殊清洗算法,每次测试,都测试全部数据,浪费时间,可以只测试那些特殊数据即可(切记).

  4. 《深入理解Spark:核心思想与源码分析》正式出版上市

    自己牺牲了7个月的周末和下班空闲时间,通过研究Spark源码和原理,总结整理的<深入理解Spark:核心思想与源码分析>一书现在已经正式出版上市,目前亚马逊.京东.当当.天猫等网站均有销售 ...

  5. UVAL1277_Cops and Thieves

    单源点汇点无向图,要阻隔某个点的流量,必须在一个点上消耗一定的价值,问你能否在消耗价值不超过k的前提下,阻隔源点到汇点的流量. 直接对于有权值的点拆点,拆后边容量即为点权.其余的点的容量无穷,最大流即 ...

  6. Big Number--hdu1018(数学)

    http://acm.hdu.edu.cn/showproblem.php?pid=1018 题目大意  : 求一个数的阶乘的位数 公式log10(n!)=log10(1)+log10(2)+log1 ...

  7. 基本套接字编程(5) -- epoll篇

    1. epoll技术 epoll是Linux内核为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃 ...

  8. Android双向滑动菜单完全解析,教你如何一分钟实现双向滑动特效

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/9671609 记得在很早之前,我写了一篇关于Android滑动菜单的文章,其中有一个 ...

  9. Node.js-提供了四种形式的定时器

    Node.js提供了四种形式的定时器 global.setTimeout(); //一次性定时器 global.setInterval(); //周期性定时器 global.nextTick(); / ...

  10. java中的匿名内部类小结

    匿名内部类也就是没有名字的内部类.正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写. 但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口. 实例1:不使用匿名内部类来实现 ...