我想知道Type
类型的on对象实际上是普通类的类型(例如Object
,Int32
等)还是类型的元 - 对象(例如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
我无法在Type
或TypeInfo
中找到任何方法/属性来判断构成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+" }
);
}
?
答案 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
运算符,但这种类型是运行时类型。