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. [Delphi编译错误]F2084 Internal Error: U2107

    看到这个错误真是头痛,这是一个很旧的项目了,想修改下东西,清理下工程一编译出现这个该死的错误,百度了下,也没解决问题.没办法只好编译所有的BPL了.   这个项目是带包编译的,而且带了几个自己的包. ...

  2. PRISM ‘VS100COMNTOOLS’ not set. Cannot set the build environment

    prism 注册dll,出现以上错误 在系统环境变量,增加 VS100COMNTOOLS 设置路径C:\Program Files (x86)\Microsoft Visual Studio 11.0 ...

  3. js 获取、清空 input type="file"的值 .(转)

    上传控件基础知识说明: 上传控件(<input type="file"/>)用于在客户端浏览并上传文件,用户选取的路径可以由value属性获取,但value属性是只读的 ...

  4. 从nib文件里加载collectionViewCell

    如何取出在xib文件里绘制的collectionViewCell ? 1.获得nib文件 UINib *nib = [[UINib NibWithName:@"xib文件的名字"] ...

  5. 超链接的#和javascript:void(0)的区别

    转载于:http://www.uw3c.com/cssviews/css12.html   在工作中,如果我们想把a标签中的链接置成空链接,我们一般会用两种方法: 1 <a href=" ...

  6. gvim 备份文件去除 配置

    默认情况下使用Vim编程,在修改文件后系统会自动生成一个带~的备份文件,看上去又乱又讨人厌. 怎么让Vim不自动生成这些备份文件呢? 1. 找到你的Vim安装目录,如果是在Windows下默认路径安装 ...

  7. Address already in use: bind

    Eclipse中报了这个错误,下拉小窗口,可以看到正在运行的项目,选中项目,都关闭就Ok了 还有一种方法就是关闭javaw.exe进程

  8. 【Python自动化运维之路Day9】Socket

    socket也可以认为是套接字是一种源IP地址和目的IP地址以及源端口号和目的端口号的组合.网络化的应用程序在开始任何通讯之前都必须要创建套接字.就像电话的插口一样,没有它就没办法通讯. socket ...

  9. centos7 安装 notejs

    1.安装集成工具 yum -y install gcc make gcc-c++ 2.安装notejs 自行选择版本:https://nodejs.org/dist/ wget https://nod ...

  10. [MSSQL2012]CUME_DIST函数

    CUME_DIST函数以某列作为基准,计算其它行相对于基准行数据的比例.差距比例,比较容易理解 先看下测试数据 DECLARE @TestData TABLE(     ID INT IDENTITY ...