mardi 11 décembre 2018

Test the type is implements the interface or not. c#

I want to know the from the System.Type is implements the interface or not. But I want to handle the generic cases as well.

There is a question in SQ where the answer is highly rated, but for my case is not a solution, for some reason:

  1. I do not have an instance of the object
  2. I want to handle the special generic classes as well. e.g.: IDictionary<,>

so when I have an instance the code is sill not a solution, because i cannot write this:

  IDictionary<,> myTest = originalObject as IDictionary<,>

because the IDictionary<,> is not a valid type. What is best way to tell the System.Type is implements an interface or not.


Basically want to extend the System.Type with this functionality so what is the best way to write this function correctly:

    public static bool ImplementsInterface( this Type type, Type interfaceType )
    {
        foreach( Type implementedType in type.GetInterfaces() )
        {
            if( interfaceType.GetTypeInfo().IsGenericType )
            {
                if( implementedType.GetTypeInfo().IsGenericType == true &&
                     implementedType.GetGenericTypeDefinition() == interfaceType )
                {
                    return true;
                }
            }
            else
            {
                if( implementedType == interfaceType )
                    return true;
            }
        }

        return false;
    }

I feel there must be a more nice way than this :) Thank you!





Aucun commentaire:

Enregistrer un commentaire