How do I check if a type is a subtype OR the type of an object?
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:
- Use Type.IsSubclassOf
- Use Type.IsAssignableFrom
isandas
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?的更多相关文章
- Check类之duplicate declaration checking/Class name generation/Type Checking
1.duplicate declaration checking /** Check that variable does not hide variable with same name in * ...
- 训练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 ...
- 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 ...
- 前台传参数时间类型不匹配:type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'
springMVC action接收参数: org.springframework.validation.BindException: org.springframework.validation.B ...
- 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 ...
- 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 ...
- 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 ...
- 解决BeanNotOfRequiredTypeException: Bean named 'XXX' must be of type XXX, but was actually of type XXX问题
Java新手,困扰了一下午. 发布时总是报这样一个错误. org.springframework.beans.factory.BeanCreationException: Error creating ...
- 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] ...
随机推荐
- 使用JMeter进行负载测试——终极指南
这篇教程讨论的是JMeter,它是一款基于Java的.集合了几个应用程序.具有特定用途的负载和性能测试工具. 本篇主要涉及的内容: 解释一下JMeter的用途 JMeter的实现方式以及采用的技术 安 ...
- JS 获取服务器时间
function getSevertime(){ var xmlHttp = new XMLHttpRequest(); xmlHttp.open("get",location.h ...
- ubuntu卸载java
Try this command: java -version If 1.6* comes then try: sudo apt-get autoremove openjdk-6-jre If 1.7 ...
- 5.2 Adapter
1 ArrayAdapter 只可以简单的显示一行文本 ArrayAdapter<String> adapter = new ArrayAdapter<String>( thi ...
- 套题 bestcoder 84
A题:Aaronson 静下心来观察就会发现1.如果m大于等于n的位数,那么n直接写成二进制形式就是最优解形式2.如果m小于n的位数,那么贪心地使得高位尽可能地多消掉n的值,因为高位少写一个数就意味着 ...
- nginx安装启动
参考:http://network.51cto.com/art/201005/198198_4.htm 下载nginx tar.gz安装包下载pcre tar.gz安装包 安装pcretar zxvf ...
- SXT_项目
30. svn服务器运行方式: svnserve:自己做实验的时候用. svn&apache结合起来用.[常用的] 29. EXTJs not Jquery[根据项目组需求] 28. tags ...
- Spring MVC静态资源处理(在applicationContex.xml文件中进行配置)
优雅REST风格的资源URL不希望带 .html 或 .do 等后缀.由于早期的Spring MVC不能很好地处理静态资源,所以在web.xml中配置DispatcherServlet的请求映射,往往 ...
- bootstrap中实现外层DIV自适应,内层DIV宽度固定且居中的布局
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="css/bo ...
- elixir 高可用系列(二) GenServer
概述 如果我们需要管理多个进程,那么,就需要一个专门的 server 来集中监控和控制这些进程的状态,启停等. OTP 平台中的 GenServer 就是对这个 server 通用部分的抽象. 利用 ...