6
votes

C # Comment vérifier si une classe implémente une interface générique?

Comment obtenir le type d'interface générique pour une instance?

Supposons ce code: P>

interface IMyInterface<T>
{
    T MyProperty { get; set; }
}
class MyClass : IMyInterface<int> 
{
    #region IMyInterface<T> Members
    public int MyProperty
    {
        get;
        set;
    }
    #endregion
}


MyClass myClass = new MyClass();

/* returns the interface */
Type[] myinterfaces = myClass.GetType().GetInterfaces();

/* returns null */
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName);


0 commentaires

5 Réponses :


0
votes
MyInterface myi = MyClass as IMyInterface;
if (myi != null) 
{
   //... it does
}

1 commentaires

Mais j'ai besoin du type, car je l'ajoute à une collection.



5
votes

Pour obtenir l'interface générique, vous devez utiliser la propriété nom em> au lieu de la propriété FULLNAME EM>:

MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
                          .GetInterface(typeof(IMyInterface<int>).Name);

Assert.That(myinterface, Is.Not.Null);


0 commentaires

1
votes

Utilisez Nom au lieu de FullName

Type myInterface = myClass.gettype (). Getterface (typeof (imyinterface). Nom );


0 commentaires

0
votes

pourquoi vous n'utilisez pas "est" déclaration? Testez ceci: xxx


0 commentaires

0
votes

Essayez le code suivant:

public static bool ImplementsInterface(Type type, Type interfaceType)
{
    if (type == null || interfaceType == null) return false;

    if (!interfaceType.IsInterface)
    {
        throw new ArgumentException("{0} must be an interface type", nameof(interfaceType));
    }

    if (interfaceType.IsGenericType)
    {
        return interfaceType.GenericTypeArguments.Length > 0
            ? interfaceType.IsAssignableFrom(type)
            : type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
    }

    return type.GetInterfaces().Any(iType => iType == interfaceType);
}


0 commentaires