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

本文探讨C#编程中反射的两个关键方法:GetMethods()用于获取类型的所有方法,而GetCustomAttributes()则用于获取类型或成员上的自定义特性。通过实例分析,深入理解这两个方法的使用和应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值