如何确定类型是否为运行时类型

本文关键字:类型 运行时 是否 何确定 | 更新日期: 2023-09-27 18:31:30

如何确定类型是否为运行时类型? 我有这个工作,但它有点笨拙:

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

如何确定类型是否为运行时类型

我猜你实际上想知道一个Type对象是否描述了Type类,但Type对象是typeof(RuntimeType)而不是typeof(Type),因此将其与typeof(Type)进行比较失败。

您可以做的是检查是否可以将Type对象描述的类型实例分配给类型为 Type 的变量。这给出了所需的结果,因为RuntimeType派生自Type

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

如果确实需要知道描述Type类的Type对象,可以使用 GetType 方法:

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

但是,由于 typeof(Type) != typeof(Type).GetType() ,您应该避免这种情况。


例子:

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

真的,唯一的麻烦是System.RuntimeTypeinternal ,所以做一些简单的事情,比如:

   if (obj is System.RuntimeType)

不编译:

CS0122 "运行时类型" 由于其保护级别而无法访问。

因此,上面@dtb的解决方案是正确的。扩展他们的答案:

void Main()
{
    object obj = "";
    // obj = new {}; // also works
    // This works
    IsRuntimeType(obj.GetType()); // Rightly prints "it's a System.Type"
    IsRuntimeType(obj.GetType().GetType()); // Rightly prints "it's a System.RuntimeType"
    // This proves that @Hopeless' comment to the accepted answer from @dtb does not work
    IsWhatSystemType(obj.GetType()); // Should return "is a Type", but doesn't
    IsWhatSystemType(obj.GetType().GetType());
}
// This works
void IsRuntimeType(object obj)
{
    if (obj == typeof(Type).GetType())
        // Can't do `obj is System.RuntimeType` -- inaccessible due to its protection level
        Console.WriteLine("object is a System.RuntimeType");
    else if (obj is Type)
        Console.WriteLine("object is a System.Type");
}
// This proves that @Hopeless' comment to the accepted answer from @dtb does not work
void IsWhatSystemType(object obj)
{
    if (obj is TypeInfo)
        Console.WriteLine("object is a System.RuntimeType");
    else
        Console.WriteLine("object is a Type");
}

在这里工作 .NET 摆弄。

return type == typeof(MyObjectType) || isoftype(type.BaseType) ;