如何确定是否一类是RunTimeType的? [英] How to determine if a Type is of RunTimeType?

查看:231
本文介绍了如何确定是否一类是RunTimeType的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定一个类型的类型RunTimeType的?我有这个工作,但它是一种缺憾:

 私人布尔IsTypeOfType(type类型)
{
返回type.FullName ==System.RuntimeType
}


解决方案

我猜你真正想要的要知道,如果一个键入对象描述了键入类,但键入对象 typeof运算(RuntimeType),而不是 typeof运算(类型),所以它比较 typeof运算(类型)失败。



您可以做的是检查是否由键入对象可以被分配到键入键入的变量。这使期望的结果,因为 RuntimeType 导出类型

 私人布尔IsTypeOfType(type类型)
{
返回typeof运算(类型).IsAssignableFrom(类型);
}






如果你真的需要知道描述键入类,则可以使用GetType方法的键入目标:

 私人布尔IsRuntimeType(type类型)
{
返回类型== typeof运算(类型).GetType();
}



不过,由于 typeof运算(类型)!= typeof运算(类型).GetType(),你应该避免这一点。






示例

  IsTypeOfType(typeof运算(类型))//真
IsTypeOfType(typeof运算(类型)。的GetType())//真
IsTypeOfType(typeof运算(字符串))//虚假
IsTypeOfType(typeof运算(INT))//虚假

IsRuntimeType(typeof运算(类型)) //虚假
IsRuntimeType(typeof运算(类型).GetType())//真
IsRuntimeType(typeof运算(字符串))//虚假
IsRuntimeType(typeof运算(INT))//虚假


How do I determine if a Type is of type RunTimeType? I have this working but it is kind of kludgy:

    private bool IsTypeOfType(Type type)
    {
        return type.FullName ==  "System.RuntimeType";
    }

解决方案

I guess that you actually want to know if a Type object describes the Type class, but the Type object is typeof(RuntimeType) and not typeof(Type) and so comparing it to typeof(Type) fails.

What you can do is check if a instance of the type described by the Type object could be assigned to a variable of type Type. This gives the desired result, because RuntimeType derives from Type:

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


If you really need to know the Type object that describes the Type class, you can use the GetType Method:

private bool IsRuntimeType(Type type)
{
    return type == typeof(Type).GetType();
}

However, because typeof(Type) != typeof(Type).GetType(), you should avoid this.


Examples:

IsTypeOfType(typeof(Type))                          // true
IsTypeOfType(typeof(Type).GetType())                // true
IsTypeOfType(typeof(string))                        // false
IsTypeOfType(typeof(int))                           // false

IsRuntimeType(typeof(Type))                         // false
IsRuntimeType(typeof(Type).GetType())               // true
IsRuntimeType(typeof(string))                       // false
IsRuntimeType(typeof(int))                          // false

这篇关于如何确定是否一类是RunTimeType的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆