如果传入一字符串,例如传入"mycontrol",mycontrol又是一class,但是我想用这个类,如何实现

解决方案 »

  1.   

    你是说给方法传入类?
    public void 方法名(类名 mycontrol)
    {
        //
    }
      

  2.   

    Type t = System.Type.GetType("System.String")可以得到类型
      

  3.   

    我是使用usercontrol,给某aspx传入一个ascx控件,因为传入的只是ascx的名字,即字符串名,但我想使用控件中的类,该如何实现
      

  4.   

    protected void Page_Load(object sender, EventArgs e)
        {
            string controlName = Request.QueryString["uc"];
            Type MyControl = System.Type.GetType(controlName);
            UserControl control = (UserControl)LoadControl(controlName+".ascx");
            ph.Controls.Add(control);
            //strSql = (control as mycontrol).getSqlString();
            Response.Write(strSql);    }
    这是调用的代码,controlName就是传入的字符串,注释的就是我想实现的
      

  5.   

    可以用反射来做,
    /// <summary>
    /// 执行指定的方法
    /// </summary>
    /// <param name="FilePath">方法所在的文件路径</param>
    /// <param name="ClassName">方法所在的命名空间及类名称</param>
    /// <param name="FunctionName">方法名称</param>
    /// <param name="Para">参数集合</param>
    public static void RunReflection(string FilePath, string ClassName, string FunctionName, object[] Para)
    {
    try
    {
    System.Reflection.Assembly A = Assembly.LoadFrom(FilePath);
    Type t = A.GetType(ClassName);
    Console.WriteLine(ClassName);
    object obj = Assembly.GetAssembly(t).CreateInstance(ClassName);//创建实例 MethodInfo method = t.GetMethod(FunctionName);//提取方法信息
    method.Invoke(obj, Para);//调用方法
    }
    catch(Exception e)
    {
    throw new Exception("执行失败!" + "\n" + e.Message);
    }
    }
      

  6.   

    System.Reflection.Assembly A = Assembly.LoadFrom(FilePath);
    这里的lord是指从dll中lord吧,我的文件是用户自定义控件,xxx.ascx文件
    好像行不通
      

  7.   

    对,是从dll里调的,如果这样不行不知道用工厂类做行不行,参考这个:http://www.jdon.com/designpatterns/designpattern_factory.htm