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);
5 Réponses :
MyInterface myi = MyClass as IMyInterface; if (myi != null) { //... it does }
Mais j'ai besoin du type, car je l'ajoute à une collection.
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);
Utilisez Nom Strong> au lieu de FullName strong> p>
Type myInterface = myClass.gettype (). Getterface (typeof (imyinterface). Nom strong>);
p>
pourquoi vous n'utilisez pas "est" déclaration? Testez ceci:
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); }