Note that there are some explanatory texts on larger screens.

plurals
  1. PORetrieving a Type's leaf interfaces
    text
    copied!<p>The <a href="http://msdn.microsoft.com/en-us/library/system.type.aspx" rel="nofollow noreferrer">System.Type</a> class provides a <a href="http://msdn.microsoft.com/en-us/library/system.type.getinterfaces.aspx" rel="nofollow noreferrer">GetInterfaces</a>() method that "gets all the interfaces implemented or inherited by the current Type". The problem is that "The GetInterfaces method does not return interfaces in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which interfaces are returned, because that order varies". In my case, however, I need to isolate and expose (via WCF) only the leaf interfaces of the interface hierarchy, that is interfaces that are not inherited by other interfaces in that hierarchy. For example, consider the following hierarchy</p> <pre><code>interface IA { } interface IB : IA { } interface IC : IB { } interface ID : IB { } interface IE : IA { } class Foo : IC, IE {} </code></pre> <p>Foo's leaf interfaces are IC and IE, whereas GetInterfaces() will return all 5 interfaces (IA..IE). A <a href="http://msdn.microsoft.com/en-us/library/system.type.findinterfaces.aspx" rel="nofollow noreferrer">FindInterfaces</a>() method is also provided, allowing you to filter the aforementioned interfaces using a predicate of your choice.</p> <p>My current implementation is given below. It is O(n^2) where n is the number of interfaces the type implements. I was wondering if there was a more elgant and/or efficient way of doing it.</p> <pre><code> private Type[] GetLeafInterfaces(Type type) { return type.FindInterfaces((candidateIfc, allIfcs) =&gt; { foreach (Type ifc in (Type[])allIfcs) { if (candidateIfc != ifc &amp;&amp; candidateIfc.IsAssignableFrom(ifc)) return false; } return true; } ,type.GetInterfaces()); } </code></pre> <p>Thanks in advance</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload