C #: check if an object implements any list of interfaces?

I want to check if a type implements one of a set of interfaces.

ViewData["IsInTheSet"] = model.ImplementsAny<IInterface1, IInterface2, IInterface3, IInterface4>(); 

For this, I wrote the following extension methods.

Is there a more extensible way to write the following code? I would prefer not to write a new method when using generics.

  public static bool Implements<T>(this object obj) { Check.Argument.IsNotNull(obj, "obj"); return (obj is T); } public static bool ImplementsAny<T>(this object obj) { return obj.Implements<T>(); } public static bool ImplementsAny<T,V>(this object obj) { if (Implements<T>(obj)) return true; if (Implements<V>(obj)) return true; return false; } public static bool ImplementsAny<T,V,W>(this object obj) { if (Implements<T>(obj)) return true; if (Implements<V>(obj)) return true; if (Implements<W>(obj)) return true; return false; } public static bool ImplementsAny<T, V, W, X>(this object obj) { if (Implements<T>(obj)) return true; if (Implements<V>(obj)) return true; if (Implements<W>(obj)) return true; if (Implements<X>(obj)) return true; return false; } 
+4
source share
2 answers

Why not use something like the following:

 public static bool ImplementsAny(this object obj, params Type[] types) { foreach(var type in types) { if(type.IsAssignableFrom(obj.GetType()) return true; } return false; } 

Then you can call it like this:

 model.ImplementsAny(typeof(IInterface1), typeof(IInterface2), typeof(IInterface3), typeof(IInterface4)); 
+5
source

Interface Verification Method:

 public static bool IsImplementationOf(this Type checkMe, Type forMe) { if (forMe.IsGenericTypeDefinition) return checkMe.GetInterfaces().Select(i => { if (i.IsGenericType) return i.GetGenericTypeDefinition(); return i; }).Any(i => i == forMe); return forMe.IsAssignableFrom(checkMe); } 

This can easily be extended to:

 public static bool IsImplementationOf(this Type checkMe, params Type[] forUs) { return forUs.Any(forMe => { if (forMe.IsGenericTypeDefinition) return checkMe.GetInterfaces().Select(i => { if (i.IsGenericType) return i.GetGenericTypeDefinition(); return i; }).Any(i => i == forMe); return forMe.IsAssignableFrom(checkMe); }); } 

Or even better:

 public static bool IsImplementationOf(this Type checkMe, params Type[] forUs) { return forUs.Any(forMe => checkMe.IsImplementationOf(forMe)); } 

Warning: not indexed

Then just typeof your type parameters before passing them to this.

+1
source

Source: https://habr.com/ru/post/1404028/


All Articles