Getting type arguments of generic interfaces that a class implements

后端 未结 3 2119
孤街浪徒
孤街浪徒 2020-12-24 12:16

I have a generic interface, say IGeneric. For a given type, I want to find the generic arguments which a class imlements via IGeneric.

It is more clear in this examp

相关标签:
3条回答
  • 2020-12-24 12:22
      Type t = typeof(MyClass);
                List<Type> Gtypes = new List<Type>();
                foreach (Type it in t.GetInterfaces())
                {
                    if ( it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IGeneric<>))
                        Gtypes.AddRange(it.GetGenericArguments());
                }
    
    
     public class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { }
    
        public interface IGeneric<T>{}
    
        public interface IDontWantThis<T>{}
    
        public class Employee{ }
    
        public class Company{ }
    
        public class EvilType{ }
    
    0 讨论(0)
  • 2020-12-24 12:23

    To limit it to just a specific flavor of generic interface you need to get the generic type definition and compare to the "open" interface (IGeneric<> - note no "T" specified):

    List<Type> genTypes = new List<Type>();
    foreach(Type intType in t.GetInterfaces()) {
        if(intType.IsGenericType && intType.GetGenericTypeDefinition()
            == typeof(IGeneric<>)) {
            genTypes.Add(intType.GetGenericArguments()[0]);
        }
    }
    // now look at genTypes
    

    Or as LINQ query-syntax:

    Type[] typeArgs = (
        from iType in typeof(MyClass).GetInterfaces()
        where iType.IsGenericType
          && iType.GetGenericTypeDefinition() == typeof(IGeneric<>)
        select iType.GetGenericArguments()[0]).ToArray();
    
    0 讨论(0)
  • 2020-12-24 12:43
    typeof(MyClass)
        .GetInterfaces()
        .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
        .SelectMany(i => i.GetGenericArguments())
        .ToArray();
    
    0 讨论(0)
提交回复
热议问题