c# - 确定类型是否是泛型类型的子类

标签 c# generics reflection

class Program
{
    static void Main(string[] args) {
        Check(new Foo());
        Check(new Bar());
    }
    static void Check<T>(T obj) {
        // "The type T cannot be used as type parameter..."
        if (typeof(T).IsSubclassOf(typeof(Entity<T>))) {
            System.Console.WriteLine("obj is Entity<T>");
        }
    }
}
class Entity<T> where T : Entity<T>{ }
class Foo : Entity<Foo> { }
class Bar { }

编译这个东西的正确方法是什么?我可以继承Entity<T>来自非通用 EntityBase类,或者可以尝试 typeof(Entity<>).MakeGenericType(typeof(T))看看它是否成功,但有没有办法不滥用 try { } catch { }阻止或破坏类型层次结构?

关于Type有一些方法看起来很有用,比如 GetGenericArgumentsGetGenericParameterConstraints但我完全不知道如何使用它们......

最佳答案

这样的事情应该可行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4 {
    class Program {
        static void Main(string[] args) {
            Check(new Foo());
            Check(new Bar());
            Console.ReadLine();
        }
        static void Check<T>(T obj) {
            // "The type T cannot be used as type parameter..."
            if (IsDerivedOfGenericType(typeof(T), typeof(Entity<>))) {
                System.Console.WriteLine(string.Format("{0} is Entity<T>", typeof(T)));
            }
        }

        static bool IsDerivedOfGenericType(Type type, Type genericType) {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
                return true;
            if (type.BaseType != null) {
                return IsDerivedOfGenericType(type.BaseType, genericType);
            }
            return false;
        }
    }
    class Entity<T> where T : Entity<T> { }
    class Foo : Entity<Foo> { }
    class Bar { }
}

关于c# - 确定类型是否是泛型类型的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17058697/

相关文章:

c# - MVC ViewModel 未在 View 中填充

c# - 参数错误

c# - 将数值具体类型转换为数值泛型

java - 在 Java-8 中自动将属性名称作为参数传递

c# - Html.CheckBoxFor 类型转换错误

c# - 使另一个类中的方法在完成后调用调用类中的事件?

java - 当 Enum 的字符串表示和类型在运行时已知时如何获取 Enum?

c# - 有没有办法在没有泛型约束的情况下强制执行无参数构造函数

java - 当无法泛化时,正确转换为作为参数传递的未知类型

c# - 不使用反射获取属性值