Get All Interface Members - CSharp System.Reflection

CSharp examples for System.Reflection:Interface

Description

Get All Interface Members

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;/*w w  w . ja v a2s  .com*/
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static List<MemberInfo> GetAllInterfaceMembers(this Type t)
        {
            if (!t.IsInterface()) throw new Exception("Expected interface, found: " + t);

            var pending = new Stack<Type>();
            pending.Push(t);

            var ret = new List<MemberInfo>();

            while (pending.Count > 0)
            {
                var current = pending.Pop();

                ret.AddRange(current.GetMembers());

                if (current.BaseType() != null)
                {
                    pending.Push(current.BaseType());
                }

                current.GetInterfaces().ForEach(i => pending.Push(i));
            }

            return ret;
        }
        public static bool IsInterface(this Type type)
        {
            var info = type.GetTypeInfo();

            return info.IsInterface;
        }
        public static Type BaseType(this Type type)
        {
            var info = type.GetTypeInfo();

            return info.BaseType;
        }
        public static void ForEach<T>(this IEnumerable<T> e, Action<T> func)
        {
            foreach (var x in e)
            {
                func(x);
            }
        }
}

Related Tutorials