用运行时已知的对象类型替换 'is'

Substitute for 'is' with types of object known in runtime

我正在尝试检查某些 Type 是否是另一个 Type 的实例。就像在这个简单的方法中一样,最好的选择是:

bool Example(Type instance, Type runtimeKnwownType) {
    return instance is runtimeKnwownType;
}

这是最佳选择,因为 is 适用于接口,但它不适用于 Type 并且不是常量右操作数。另一种选择是 Type.IsSubclassOf(object) 不适用于接口。所以我的问题是在这种情况下替换 is

您可以 GetType 两个对象:

public Class1 abc;
public Class2 def;
public void Test()
{
    if (abc.GetType() == def.GetType())
    {

    }
}

或者

public bool Example(Type instance, Type runtimeKnwownType)
{
    return instance == runtimeKnwownType;
}

根据您的评论,您想检查两种类型的分配。你能试试 this:

Type.IsAssignableFrom(Type c)

"True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."