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. 设置EditText光标位置

    editext.setSelection(int index);

  2. lsslot

    lsslot 命令 用途 显示动态可重新配置的插槽(比如热插拔)及其特性. 语法 lsslot -c ConnectorType [ -a | -o | -l DeviceName | -s Slot ...

  3. ycsb-命令及参数-与生成的负载类型相关

    loadbin/ycsb load mydb -P workloads/workloada -p "mydb.host=127.0.0.1" -p "mydb.port= ...

  4. 【java】:解析xml

    ==========================================xml文件<?xml version="1.0" encoding="GB231 ...

  5. [Chapter 3 Process]Practice 3.12 Including the initial parent process, how many processes are created by the program shown in Figure 3.32?

    3.12 Including the initial parent process, how many processes are created by the program shown in Fi ...

  6. hibernate报错及解决方式

    1 java.sql.BatchUpdateException: ORA-01438: 值大于为此列指定的允许精度 原因:pl/sql number(n),插入的位数大于n

  7. 有关big.LITTLE,你需要知道的十件事情

    来源 问题 1:该技术能够同时打开所有核心吗?   在早期的 big.LITTLE 软件模型中(集群迁移和 CPU 迁移),软件在核心之间切换,不能同时打开所有核心.在更新的软件模型“全局任务调度”中 ...

  8. whatweb

    WhatWeb是一款网站指纹识别工具,主要针对的问题是:“这个网站使用的什么技术?”WhatWeb可以告诉你网站搭建使用的程序,包括何种CMS系统.什么博客系统.Javascript库.web服务器. ...

  9. AngularJs的$http使用随笔

    AngularJs的$http服务是Angularjs自带的核心服务之一,用来与HTTP远程服务器交互. 关于$http使用,我体会的一下几点注意: 1.在使用是报“Uncaught Referenc ...

  10. 天气预报数据API

    http://www.weather.com.cn/data/cityinfo/101010100.html//过期: http://api.36wu.com/Weather/GetMoreWeath ...