Csharp/C Sharp/Reflection/BindingFlags

Материал из .Net Framework эксперт
Версия от 11:38, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Print Method Info: BindingFlags

 
using System;
using System.Collections;
using System.Reflection;
public class MainClass{
    public static void Main() {
        Assembly LoadedAsm = Assembly.LoadFrom("yourName");
        Console.WriteLine(LoadedAsm.FullName);
        Type[] LoadedTypes = LoadedAsm.GetTypes();
        if (LoadedTypes.Length == 0) {
            Console.WriteLine("\tNo Types!");
        } else {
            Console.WriteLine("\tFound Types:");
            foreach (Type t in LoadedTypes) {
                if (t.IsPublic && !t.IsEnum && !t.IsValueType) {
                    Console.WriteLine("Type: {0}", t.FullName);
                    PrintMethodInfo(t);
                }
            }
        }
    }
    private static void PrintMethodInfo(Type t) {
        MethodInfo[] methods = t.GetMethods(BindingFlags.DeclaredOnly |
            BindingFlags.Public | BindingFlags.Instance |
            BindingFlags.Static);
        foreach (MethodInfo m in methods) {
            if (m.IsStatic)
                Console.WriteLine("Static Method: {0}", m.Name);
            else
                Console.WriteLine("Method: {0}", m.Name);
            Console.WriteLine("\tReturns {0}", m.ReturnType.FullName);
            ParameterInfo[] pList = m.GetParameters();
            if (pList.Length == 0) {
                Console.WriteLine("\tNo Parameters");
            } else {
                Console.WriteLine("\tParameter List:");
                foreach (ParameterInfo p in pList) {
                    Console.WriteLine("\t\t{0} {1}", p.ParameterType.FullName,p.Name);
                }
                Console.WriteLine();
            }
        }
    }
}


Use BindingFlags Instance and NonPublic

using System;
using System.Reflection;
class DumpType {
    public static void Main() {
        MyClass zObj = new MyClass();
        Type tObj = zObj.GetType();
        MemberInfo[] members = tObj.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic);
        foreach (MemberInfo member in members) {
            Console.WriteLine(member.Name);
        }
        members = tObj.GetMembers(BindingFlags.Public | BindingFlags.Static);
        Console.WriteLine(" ");
        foreach (MemberInfo member in members) {
            Console.WriteLine(member.Name);
        }
    }
}
class MyClass {
    private int vara = 5;
    public int PropA {
        get {
            return vara;
        }
    }
    static public void MethodA() {
        Console.WriteLine("MyClass::MethodA called.");
    }
}