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

C#反射问题

  •  4
  • jamesaharvey  · 技术社区  · 16 年前

    我在使用反射时遇到了以下问题。

    以下语句的评估结果为false:

    object[] attributes = someType.GetCustomAttributes(true);
    
    if (attributes[0] is NUnit.Framework.TestFixtureAttribute)
        return true;
    

    然而,这被评估为真:

    object[] attributes = someType.GetCustomAttributes(true);
    
    if (attributes[0].ToString() == "NUnit.Framework.TestFixtureAttribute")
        return true;
    

    知道为什么吗?

    2 回复  |  直到 16 年前
        1
  •  8
  •   Jon Skeet    16 年前

    比较 attributes[0].GetType().Assembly 随着 typeof(NUnit.Framework.TestFixtureAttribute).Assembly .

    只需执行引用类型比较-即使是两个 Assembly 实例是从完全相同的文件加载的,如果它们是两个单独的实例,则从它们创建的任何类型都是不同的(使得 is 失败)。

        2
  •  3
  •   Philippe Leybaert    16 年前