当你有 System.Type 时比较类型

Comparing type when you have a System.Type

我有以下代表:

Action<string, object, Type> IsA = 
    (name, candidate, target) => 
    {
        Write("Is " + name + " a " + target.Name + "? " + (candidate.GetType() is target));
    };        

应该return候选人是否是一个目标。但是,target 现在是 System.Type.

的变量

我怎么说 candidate 是不是 target

你可以做简单的比较:

candidate.GetType() == target;

它将检查 candidate 是否正是 target 中指定的类型。 如果你想包含 subclasses/interfaces 你可以这样写:

target.IsAssignableFrom(candidate.GetType());

它的工作方式类似于 is 关键字,但在 Type class 上运行,而不是具体实例。

您还应该检查 candidate 是否不为空 - 在这种情况下 GetType 将抛出 NullReferenceException 异常。