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
is
andas
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 Base
is (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] ...
随机推荐
- OA项目之导入
内容显示页: protected void btnIMP_Click(object sender, EventArgs e) { Response.Redire ...
- Ubuntu 12.04(32位)安装Oracle 11g(32位)
安装过程(主要过程就直接copy别人的教程了)及问题: 1.将系统更新到最新: sudo apt-get updatesudo apt-get dist-upgrade 2. 如果使用的Ubuntu不 ...
- iOS(OC)中的冒泡排序
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"12",@"84", @"35& ...
- cocos2d-x源码分析(1)
class CC_DLL CCCopying { public: virtual CCObject* copyWithZone(CCZone* pZone); }; class CC_DLL CCZo ...
- 1057. Stack (30)
分析: 考察树状数组 + 二分, 注意以下几点: 1.题目除了正常的进栈和出栈操作外增加了获取中位数的操作, 获取中位数,我们有以下方法: (1):每次全部退栈,进行排序,太浪费时间,不可取. (2) ...
- 7.5 [bx+idata] 书中错误
这节中的问题 7.1 有错误 题目和我自己的注释为: 用 Debug 查看内存,结果如下: 2000:1000 BE 00 06 00 00 00 ... 写出下面程序执行后,ax,bx,cx中的内容 ...
- C# 特殊处理使用方法
1.时间处理 Model.PiDaiTime.ToString("yyyyMMdd") == "00010101" ? DateTime.Now.ToStrin ...
- Restful风格API接口开发springMVC篇
Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
- Oracle数据库11g基于rehl6.5的配置与安装
REDHAT6.5安装oracle11.2.4 ORACLE11G R2官档网址: http://docs.oracle.com/cd/E11882_01/install.112/e24326/toc ...
- Android横竖屏切换小结
Android横竖屏切换小结 (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com/franksunny/635350788930000000.pdf) And ...