代码之家  ›  专栏  ›  技术社区  ›  JDMX

“is”操作符是如何在内部工作的

  •  6
  • JDMX  · 技术社区  · 15 年前

    我想比较一个对象的类型和一个类型,看看它们是否相同。我没有对象,只有对象的类型。

    我能做到 type1 == type2

    我可以有一个递归循环,在这里我重复上面的步骤 type1.BaseType 直到BaseType为null。

    我能做到 type1.GetInterface( type2.FullName ) != null 检查type2是否是type1的接口

    如果我把它们放在一起

    if ( type2.IsInterface )
      return type1.GetInterface( type2.FullName ) != null;
    
    while ( type1 != null ) {
      if ( type1 == type2 )
        return true;
    
      type1 = type1.BaseType;
    }
    return false;
    

    就这些吗 is 关键字是。我找不到合适的关键字插入反射器搜索找到的功能和谷歌搜索“是”不是真的有帮助

    1 回复  |  直到 15 年前
        1
  •  6
  •   Matthew Flaschen    15 年前

    is (§第14.9.10条 the standard )一般用途 isinst ,但如果编译时类型通过某些转换是兼容的,则不需要这样做。

    与类型对象等价的(相反)是 IsAssignableFrom . 所有这些都是正确的:

    "foo" is String;
    "foo" is object;
    
    typeof(String).IsAssignableFrom("foo".GetType());
    typeof(object).IsAssignableFrom("foo".GetType());