System.Type究竟是个什么样的类?(其虚方法问题)

为了查看某个对象的类是否定义了某个custom attribute,我写了这样的代码

Type ty=someObject.GetType();
Console.Writeline(ty.IsDefined(someAttributeType,false).ToString());

问题出在这个Type.IsDefined()函数上,System.Type继承自System.Reflection.MemberInfo, MemberInfo.IsDefined()是一个抽象函数(在il代码上有abstract字样,而且没有任何实现代码),更奇怪的是Type类并没有重写这个函数,.net framework文档上的解释是“在派生类中被重写时,指示是否在该成员上定义了一个或多个 attributeType 实例。”。难道我的ty对象的实际类型不是Type,而是Type的某个派生类?那么Object.GetType()返回的对象的类型也是一个Type的派生类。如果是这样的话,那么Type类的角色就类似于一个抽象类了?

---------------------------------------

每次typeof(xxx)或者xxx.GetType()时,实际上是返回一个System.RuntimeType类型
这个类型继承自System.Type,当然就可以当作System.Type用
这也是为什么abstract函数居然也可以直接调用

可以如此试验:
Type t1 = typeof(string);
Type t2 = t1.GetType();
Console.WriteLine(t1); // System.String
Console.WriteLine(t2); // System.RuntimeType

使用Reflector查看,System.RuntimeType确实有相关实现
比如IsDefined方法:
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
{
throw new ArgumentNullException("attributeType");
}
return CustomAttribute.IsDefined(this, attributeType, inherit);
}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus