是否所有Type类都继承自RuntimeType?

时间:2015-10-24 11:02:46

标签: c# reflection portable-class-library

我想知道Type类型的on对象实际上是普通类的类型(例如ObjectInt32等)还是类型的元 - 对象(例如typeof(Object)typeof(Int32)等)。

通过对象的类型我的意思是:

Type t = typeof(Object);
Console.WriteLine("Type is {0}", t.FullName);
  

Type是System.Object

通过类型对象的类型,即元对象

Type t = typeof(Object).GetType();
Console.WriteLine("Type is {0}", t.FullName);
  

Type为System.RuntimeType

我无法在TypeTypeInfo中找到任何方法/属性来判断构成Type对象的对象实际上是Type而不是一个普通的对象。

如果我有这个对象,我可以这样做:

bool IsType(object o) { return o is Type; }

但是,我没有对象本身,只有它的类型。

我希望有一些事情:

bool IsType(Type t) { return t.GetTypeInfo().IsType; }

但似乎并没有这样,似乎......

所以我到目前为止唯一能想到的是:

bool IsType(Type type)
{
    // Can't use typeof(RuntimeType) due to its protection level
    Type runtimeType = typeof(Object).GetType();
    return runtimeType.Equals(type);
}

但是,我无法确定GetType()类型Type的所有对象RuntimeType都会返回Type,而且它们实际上也不会继承它......

更新

让我更好地解释一下。我正在写一个序列化器。序列化类成员(例如字段或属性)时,我将拥有字段类型(但不是对象)。成员完全可能属于class MyClass { private Type _cachedType; } 类型。我也希望能够序列化这些对象。

例如像这样的类:

_cachedType

我将通过反射得到字段Type的类型。我怎么知道对象首先是public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); routes.MapRoute( "Contests", "Contests/{id}/{action}", new { controller = "Contests", action = "Manage" }, new { id = @"\d+" } ); }

2 个答案:

答案 0 :(得分:1)

好的,我认为整个问题都缩小为

  

如何确定字段的类型为Type

据我所知,你不关心存储在那里的值的实际类型,因为你将以相同的方式序列化所有值(“然后我可以使用Type.AssemblyQualifiedName将它们序列化为字符串”)。

你走了:

bool IsType(Type type)
{
    return type == typeof(Type);
}

无需进行子类检查。实际对象将是子类,但该字段将具有类型Type

如果您愿意,可以添加子类检查:

bool IsType(Type type)
{
    return typeof(Type).IsAssignableFrom(type);
}

答案 1 :(得分:0)

我想我明白了。我可以使用TypeInfo.IsAssignableFrom

bool IsType(Type type)
{
    TypeInfo info = typeof(Type).GetTypeInfo();
    return info.IsAssignableFrom(type.GetTypeInfo());
}

这大致等同于在对象上使用is运算符,但这种类型是运行时类型。