How to compare object's type with a generics type, irrelevant to generic argument?

前端 未结 1 1656
说谎
说谎 2021-02-07 12:18

Best way to illustrate my question is with this example code:

  class Item {}
  class Container< T > {}
  class Program
  {
    static void DoSomething( ob         


        
1条回答
  •  情深已故
    2021-02-07 12:22

    Try:

    typeof(Container<>) == something.GetType().GetGenericTypeDefinition()
    

    Note that this will only return true if the actual type is Container. It doesn't work for derived types. For instance, it'll return false for the following:

    class StringContainer : Container
    

    If you need to make it work for this case, you should traverse the inheritance hierarchy and test each base class for being Container:

    static bool IsGenericTypeOf(Type genericType, Type someType)
    {   
      if (someType.IsGenericType 
              && genericType == someType.GetGenericTypeDefinition()) return true;
    
      return someType.BaseType != null 
              && IsGenericTypeOf(genericType, someType.BaseType);
    }
    

    0 讨论(0)
提交回复
热议问题