C\#반사 와 사용자 정의 속성 을 통 해 호출 방법

9055 단어 C#
반사 호출 방법 은 구조 에 사용 할 수 있 으 며,먼저 인터페이스 를 써 서 뒤의 상황 을 구체 적 으로 실현 할 수 있다.
특정 사용 방법 에 대해 서 는 특별 속성 을 표시 할 수 있 습 니 다.

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Reflection;

namespace ReflectMethod
{
    //      
    [AttributeUsage(AttributeTargets.All)]
    class GameSystem : Attribute//     GameSystemAttribute   
    {
        public GameSystem() { }

    }

    //     player 
    class player
    {

        //GameSystem      ,                GameSystemAttribute         

        [GameSystem]// start    
        public void start()
        {
            Console.WriteLine("GameSystem  start");
        }


      
        public void Updata()
        {
            Console.WriteLine("my  updata");
        }
    }

    class Program
    {
        
        static void Main(string[] args)
        {
            //           
            Type[] types = typeof(Program).Assembly.GetTypes();


            foreach (Type t in types)
            {

                AttributeLogic(t);
            }
            Console.ReadKey();


        }
        static void AttributeLogic(Type type)
        {
            //       
            foreach (MethodInfo method in type.GetMethods())
            {
                //       
                foreach (Attribute attr in method.GetCustomAttributes())
                {
                    //          
                    if (attr is GameSystem)
                    {
                        //    
                        object reflectTest = Activator.CreateInstance(type);
                        //       
                        MethodInfo methodInfo = type.GetMethod(method.Name);
                        //    
                        methodInfo.Invoke(reflectTest, null);
                    }
                }
            }

        }


      
    }


   
      
    


}

좋은 웹페이지 즐겨찾기