c# - 如何判断一个Type是不是RunTimeType?

标签 c#

如何确定 Type 是否属于 RunTimeType 类型?我有这个工作,但有点笨拙:

    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

关于c# - 如何判断一个Type是不是RunTimeType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183619/

相关文章:

c# - 使用 TPT 方法的多对多 Entity Framework

c# - DataTemplate 无法解析 DataType 前缀数据

c# - 为什么ᏌᏊ ᎢᏳᎾᎵᏍᏔᏅ ᏍᎦᏚᎩ是美国的本土名称?

c# - 在 C# 和 C++ 之间传输图像数据

c# - 有和没有 "new"的接线事件之间的区别

c# - 头脑 Storm : How to arrange DateTime to particular interval frame?

c# - SqlBulkInsert 和 Guid 问题

c# - POST 表单数组没有成功

c# - 如何创建一个行为类似于 Session[] 集合的集合? C#

c# - .Net 全局化在特定服务器上无法正常工作