Getting sheet type interfaces

The System.Type class provides GetInterfaces (), which "gets all the interfaces implemented or inherited by the current type." The problem is that "the GetInterfaces method does not return interfaces in a specific order, for example, in alphabetical order or in the order of declaration. Your code should not depend on the order in which the interfaces are returned, as this order changes." In my case, however, I need to isolate and expose (via WCF) only the interfaces of the interface hierarchy sheet, that is, interfaces that are not inherited by other interfaces in this hierarchy. For example, consider the following hierarchy

interface IA { }
interface IB : IA { }
interface IC : IB { }
interface ID : IB { }
interface IE : IA { }
class Foo : IC, IE {}

Foo line interfaces are IC and IE, while GetInterfaces () will return all 5 interfaces (IA..IE). The FindInterfaces () method is provided , allowing you to filter the above interfaces using the predicate of your choice.

My current implementation is given below. This is O (n ^ 2), where n is the number of interfaces that the type implements. I was wondering if there is a more elgant and / or effective way to do this.

    private Type[] GetLeafInterfaces(Type type)
    {
        return type.FindInterfaces((candidateIfc, allIfcs) =>
        {
            foreach (Type ifc in (Type[])allIfcs)
            {
                if (candidateIfc != ifc && candidateIfc.IsAssignableFrom(ifc))
                    return false;    
            }
            return true;
        }
        ,type.GetInterfaces());
    }

Thank you in advance

+3
source share
1 answer

, . , Foo , . Foo Ildasm - , . :

interface IFirst { }
interface ISecond : IFirst { }
class Concrete : ISecond { }

IL- ( Ildasm):

.class private auto ansi beforefieldinit MyNamespace.Concrete
       extends [mscorlib]System.Object
       implements MyNamespace.ISecond,
                  MyNamespace.IFirst
{
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Concrete::.ctor

} // end of class MyNamespace.Concrete

, Concrete .

+3

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


All Articles