C# 클래스 이름으로 클래스 반사 인스턴스화

5876 단어 C#
대상을 대상으로 프로그래밍을 할 때 이러한 문제에 부딪힐 수 있다. 한 부류에 여러 개의 부류가 있기 때문에 부류의 대상을 만들고 그 다음에 조건에 따라 구체적인 부류를 실례화한 다음에 조작을 해야 한다.물론if else나 switch로 해도 되지만 후기의 확장성이 좋지 않다. 특히 이런 종류를 dll로 봉하여 다른 사람에게 제공하는 것은 더욱 적합하지 않다.이때 반사는 좋은 해결 방안을 제공했다.사용도 편리해요.
  • 우선 네임스페이스 도입
  • using System.Reflection;
  • 로드 프로그램 세트
  • Assembly assembly = Assembly.LoadFile(" , "); //  (EXE   DLL)
    Assembly assembly = Assembly.GetExecutingAssembly(); //  
  • 조건에 따라 실례화 대상
  •  //  , ,  object  , 
     object obj = assembly.CreateInstance(); 
     //  , ,  object  , 
     object obj = Assembly.GetExecutingAssembly().CreateInstance(" ( )", true, System.Reflection.BindingFlags.Default, null,   object[] , null, null)

    다음은 제가 직접 사용한 예입니다.
    /// 
            ///  
            /// 
            ///  
            ///  
            ///  
            ///  
            /// 
            public static T CreateInstance(string nameSpace,string className, object[] parameters)
            {
                try
                {
                    string fullName = nameSpace + "." + className;// . 
                    object ect = Assembly.GetExecutingAssembly().CreateInstance(fullName, true, System.Reflection.BindingFlags.Default, null, parameters, null, null);// ,   .   
                    return (T)ect;// 
                }
                catch
                {
                    // , 
                    return default(T);
                }
            }

    这是初步封装的函数,后面更具需要进一步封装成需要的函数,调用上面函数是在IoManager类中。

     /// 
            ///  
            /// 
            ///  , getPluginType  
            ///  
            /// 
            public static PluginBase CreateInstance(string className, TableInfo tableInfo)
            {
                object[] parameters = new object[1];
                parameters[0] = tableInfo;
                return IoManager.CreateInstance("DataTransformApplication.PluginManage", className, parameters);
            }

    在实际调用中,上面函数是在PluginBase类中。

    PluginBase NetPlugin = PluginBase.CreateInstance(this.PluginModelName,tableInfo);

    이렇게 하면 PluginBase 부모 클래스의 서브클래스 이름과 구조 클래스에 필요한 TableInfo 매개 변수에 따라 PluginBase의 대상을 PluginBase 서브클래스의 실례를 실례화할 수 있다.

    좋은 웹페이지 즐겨찾기