RT,又或者能否将字符串转换为该名字为该字符串的类型?谢谢

解决方案 »

  1.   

    反射的例子我做了一个。
    /// <summary>
            /// Invoke the function
            /// </summary>
            /// <param name="moudle">moudle</param>
            /// <param name="action">action</param>
            public static void Invoke(string moudle, string action)
            {
                //Get the view's dll
                string dll = Util.AppSettingManager.GetAppSetting("mvc");            //Get the object
                object obj = Assembly.Load(dll).CreateInstance(dll + "." + Config.GetMoudleName(moudle));            //Invoke the method
                if (obj != null)
                {
                    MethodInfo objMethod = null;
                    //Init the page
                    objMethod = obj.GetType().GetMethod("InitPage");
                    objMethod.Invoke(obj, null);
                    //Invoke the method
                    objMethod = obj.GetType().GetMethod(Config.GetActionName(action));
                    if (objMethod != null)
                    {
                        objMethod.Invoke(obj, null);
                    }
                    //Show page info
                    objMethod = obj.GetType().GetMethod("ShowPage");
                    objMethod.Invoke(obj, null);
                    //Disponit the resourse
                    objMethod = obj.GetType().GetMethod("Dispoint");
                    objMethod.Invoke(obj, null);
                    objMethod = null;
                    obj = null;
                }
                else
                {
                    Page.Response.Write("There is not the object!");
                }
            }
      

  2.   

    上面那个主要是执行方法,自己写的MVC框架用到的,下面这个是获取实体类的属性          
    public Hashtable ModelToHashTable(object obj)
            {
                Hashtable hash = new Hashtable();
                Type model = obj.GetType();
                foreach (PropertyInfo property in model.GetProperties())
                {
                    object value = property.GetValue(obj, null);
                    string name = property.Name;
                    hash.Add(name, value);
                }
                obj = null;
                model = null;
                return hash;
            }
            
      

  3.   

    Assembly.CreatInstance得到一个object,再把这个object转换成你的类,
    Assembly assembly = Assembly.LoadFrom(.....);
    object obj = assembly.CreatInstance(....);
    MyObject myObj =(Myobject)obj;
      

  4.   

    3楼的不行吧,他都不知道MyObject 是哪个。而且如果你既然知道了MyObject ,干嘛还要反射呢,浪费资源
      

  5.   

    那只是说怎么转化啊。不知道类型的话不是还有个GetType方法嘛
    至于说浪不浪费资源,那要因需要而定呀。。
      

  6.   

    回楼上:
    -------
    如果按照你在三楼那样的话也是可以,那就需要反射的类都继承同一接口例如:
    接口IX
    实体类:X1、X2、X3
    这样的话是可以IX x=(obj.GetType())obj;------
    如果不继承同一接口的话
    你该如何去定义那个x?
    (obj.GetType()) x=(obj.GetType())obj;
    即使这样可以
    那么x....你怎么去执行它?------直接去实体化一个类和通过类名反射一个类,我相信直接实体化一个类的效率肯定要比反射高吧?