Interface Hierarchien flach machen

Thomas Darimont

Erfahrenes Mitglied
Hallo,

hier mal ein einfaches Beispiel dazu wie man die Interfacehierarchy eines Type "flachklopfen" kann.

Damit ist dann folgendes gemeint:

C#:
    public interface Bubu : A, D { }

    public interface A : B { void AA(); }
    public interface B : C { void BB(); }
    public interface C { void CC(); }
    public interface D { void DD(); }

Die Klasse Bubu implementiert die Interfaces A und D und damit
implizit auch C und B. Die Methode GetInterfaces() am Type von Bubu liefert dann alle interfaces (A,B,C,D) zurück.

Wenn man jedoch nur A,D wissen möchte kann man das folgendermaßen machen:
C#:
using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

namespace Training
{
    public class FlattenInterfaceHierarchy
    {
        public static void Main(string[] args)
        {
            Type type = typeof(Bubu);
            Type[] interfaces = type.GetInterfaces();
            Type[] flattenedInterfaces = FlattenHierarchyOf(interfaces);

            Action<Type> printAction = delegate(Type aType)
            {
                Console.Write(aType.Name);
                Console.Write(" ");
            };

            Console.Write("Interfaces: ");
            Array.ForEach<Type>(interfaces, printAction);
            Console.WriteLine();
            Console.WriteLine("########");
            Console.Write("Flattened Interface Hierarchy: ");
            Array.ForEach<Type>(flattenedInterfaces, printAction);
            Console.WriteLine();
        }


        private static Type[] FlattenHierarchyOf(Type[] interfaces)
        {
            List<Type> flattenedInterfaces = new List<Type>();
            foreach (Type iface in interfaces)
            {
                bool upperInterface = true;
                foreach (Type nestedInterface in interfaces)
                {
                    if (iface == nestedInterface)
                    {
                        continue;
                    }
                    else
                    {
                        if (null != nestedInterface.GetInterface(iface.FullName))
                        {
                            upperInterface = false;
                            break;
                        }
                    }
                }
                if (upperInterface)
                {
                    flattenedInterfaces.Add(iface);
                }
            }

            return flattenedInterfaces.ToArray();
        }
    }

    public interface Bubu : A, D { }

    public interface A : B { void AA(); }
    public interface B : C { void BB(); }
    public interface C { void CC(); }
    public interface D { void DD(); }
}

Ausgabe:
Code:
Interfaces: A B C D
########
Flattened Interface Hierarchy: A D

Gruß Tom
 
Zurück