1. 程式人生 > >c#反射中GetMethods()和GetCustomAttributes()方法

c#反射中GetMethods()和GetCustomAttributes()方法

GetMethods()例項:

using System;
using System.Reflection;
using System.Reflection.Emit;

// Create a class having two public methods and one protected method.
public class MyTypeClass
{
    public void MyMethods()
    {
    }
    public int MyMethods1()
    {
        return 3;
    }
    protected String MyMethods2()
    {
        return "hello";
    }
}
public class TypeMain
{
    public static void Main()
    {
        Type myType = (typeof(MyTypeClass));
        // Get the public methods.
        MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        Console.WriteLine("\nThe number of public methods is {0}.", myArrayMethodInfo.Length);
        // Display all the methods.
        DisplayMethodInfo(myArrayMethodInfo);
        // Get the nonpublic methods.
        MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        Console.WriteLine("\nThe number of protected methods is {0}.", myArrayMethodInfo1.Length);
        // Display information for all methods.
        DisplayMethodInfo(myArrayMethodInfo1);
        Console.ReadKey();
    }
    public static void DisplayMethodInfo(MethodInfo[] myArrayMethodInfo)
    {
        // Display information for all methods.
        for (int i = 0; i < myArrayMethodInfo.Length; i++)
        {
            MethodInfo myMethodInfo = (MethodInfo)myArrayMethodInfo[i];
            Console.WriteLine("\nThe name of the method is {0}.", myMethodInfo.Name);
        }
    }
}
輸出:
The number of public methods is 2.

The name of the method is MyMethods.

The name of the method is MyMethods1.

The number of protected methods is 1.

The name of the method is MyMethods2.

GetCustomAttributes()例項:

using System;
using System.Reflection;
using System.Reflection.Emit;

// Create a class having two public methods and one protected method.
public class MyTypeClass
{
    [System.AttributeUsage(System.AttributeTargets.Class |
                           System.AttributeTargets.Struct,
                           AllowMultiple = true)  // multiuse attribute
    ]
    public class Author : System.Attribute
    {
        string name;
        public double version;

        public Author(string name)
        {
            this.name = name;
            version = 1.0;  // Default value
        }

        public string GetName()
        {
            return name;
        }
    }

    [Author("H. Ackerman")]
    private class FirstClass
    {
        // ...
    }

    // No Author attribute
    private class SecondClass
    {
        // ...
    }

    [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
    private class ThirdClass
    {
        // ...
    }

    class TestAuthorAttribute
    {
        static void Main()
        {
            PrintAuthorInfo(typeof(FirstClass));
            PrintAuthorInfo(typeof(SecondClass));
            PrintAuthorInfo(typeof(ThirdClass));
            Console.ReadKey();
        }

        private static void PrintAuthorInfo(System.Type t)
        {
            System.Console.WriteLine("Author information for {0}", t);
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

            foreach (System.Attribute attr in attrs)
            {
                if (attr is Author)
                {
                    Author a = (Author)attr;
                    System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
                }
            }
        }
    }
}

輸出:
Author information for MyTypeClass+FirstClass
   H. Ackerman, version 1.00
Author information for MyTypeClass+SecondClass
Author information for MyTypeClass+ThirdClass
   H. Ackerman, version 1.00
   M. Knott, version 2.00

其他用法:

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ssss
{
    // Create a class having two public methods and one protected method.
    public class MyTypeClass:tttt.asd
    {
        public void MyMethods()
        {
        }
        public int MyMethods1()
        {
            return 3;
        }

        public void s()
        {
            throw new NotImplementedException();
        }

        public void s1()
        {
            throw new NotImplementedException();
        }

        protected String MyMethods2()
        {
            return "hello";
        }
    }
    public class TypeMain
    {
        public static void Main()
        {
            TypeMain aa = new TypeMain();
            Assembly assembly = aa.GetType().Assembly;
            Type[] types = assembly.GetTypes();
            Type type = typeof(tttt.asd);
            for (int i = 0; i < types.Length; i++)
            {
                if(type.IsAssignableFrom(types[i])&&!types[i].IsInterface)
                     Console.WriteLine(types[i].Name);    
            }

            Console.ReadKey();
        }
        public static void DisplayMethodInfo(MethodInfo[] myArrayMethodInfo)
        {
            // Display information for all methods.
            for (int i = 0; i < myArrayMethodInfo.Length; i++)
            {
                MethodInfo myMethodInfo = (MethodInfo)myArrayMethodInfo[i];
                Console.WriteLine("\nThe name of the method is {0}.", myMethodInfo.Name);
            }
        }


    }
}
namespace tttt
{
    public interface asd
    {

    }
}

輸出:
MyTypeClass
using System;
using System.Reflection;
using System.Reflection.Emit;

namespace TestSpace
{
    public class TestClass
    {
        private string _value;
        public TestClass()
        {
        }
        public TestClass(string value)
        {
            _value = value;
        }
        public string GetValue(string prefix)
        {
            if (_value == null)
                return "NULL";
            else
                return prefix + "  :  " + _value;
        }
        public string Value
        {
            set
            {
                _value = value;
            }
            get
            {
                if (_value == null)
                    return "NULL";
                else
                    return _value;
            }
        }
    }
}
public class TypeMain
    {
        public static void Main()
        {
            //獲取型別資訊
            Type t = Type.GetType("TestSpace.TestClass");
            //構造器的引數
            object[] constuctParms = new object[] { "timmy" };
            //根據型別建立物件
            object dObj = Activator.CreateInstance(t, constuctParms);
            //獲取方法的資訊
            MethodInfo method = t.GetMethod("GetValue");
            //呼叫方法的一些標誌位,這裡的含義是Public並且是例項方法,這也是預設的值
            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance;
            //GetValue方法的引數
            object[] parameters = new object[] { "Hello" };
            //呼叫方法,用一個object接收返回值
            object returnValue = method.Invoke(dObj, flag, Type.DefaultBinder, parameters, null);
            Console.WriteLine(returnValue);
            Console.ReadKey();
        }
    }


輸出:

Hello  :  timmy