C#比较类型是否相等,将这些类型作为参数

C# comparing types for equality, with those types as parameters

我需要在 C# 中灵活地比较类型,以测试类型的层次关系。我的第一次尝试是

public class ParentInfo<PT> {  // PT = parent type expected
    
    public static bool hasParent(LDBRootStructs item) {
        var parent = item.parent;
        var rightParent = parent is PT;  // << this is the type test I want

这很好,但这意味着在编译时将通用参数 PT 实例化为已知 class。我需要它作为一个变量,所以我尝试了这个

public static class ParentInfo2 {  // PT = parent type expected
    
    public static bool hasParent2(LDBRootStructs item,
                                      Type PT) {
        var parent = item.parent;
        var rightParent = parent is PT; <<< error here

但它抱怨说 “无法将类型 'System.Type' 隐式转换为 'LDB.LDBRootStructs'” 而且我可以' t 传入请求的类型作为参数。

我可以通过为每个 classes 添加一个测试来解决这个问题(每个 class 都有 myOwnType 虚函数,其中 returns 一个为每个 class,只是比较这些整数),但是有更简单的方法吗?我一直在看 GetType 和相关的,但不清楚。

我需要这样做来创建一个解释型 DSL,所以它必须是灵活的。 我已经在寻找以前的答案(这是 SO,它们必须存在!)但我不知道要寻找什么。

-- 编辑,意识到只是一种从 class 获取唯一 ID(字符串、整数等)的方法可能就足够了 .

这应该有效

        var foo = new Foo();
        Type bar = typeof(Foo);

        if (foo.GetType().Equals(bar))
        {

        }

您正在尝试将 class 的实例与 Type 的实例进行比较 - 这是行不通的(或者至少不会如您所愿)。

将父级的 类型 PT

类型进行比较
var rightParent = parent.GetType() == PT; 

这只会完全匹配。对于 hierarchy/inheritance 类型链,您还可以使用

var rightParent = PT.IsAssignableFrom(parent.GetType()); 

基于反射相当于

bool IsOfType<T>(object o)
{
    return o is T;
}

使用Type.IsAssignableFrom

bool IsOfType(object o, Type t)
{
    return t.IsAssignableFrom(o.GetType());
}