在C#中,有一个文本框和一个按钮,在文本框中随便输入一段代码,点击按钮时执行文本框里的代码怎么实现,帮帮忙,谢谢 

解决方案 »

  1.   

    不过微软已经提供了C#、VB和J#的,可以直接用他的
      

  2.   

    其实这样的帖子有很多,
    参考这个
    http://topic.csdn.net/u/20080307/16/b2e15b95-827e-49da-8acb-cf467368dc9a.html
      

  3.   

    例如执行一句MessageBox.show();等等
      

  4.   

    想法不错,但c#是编译型的不是解释型的,执行javascript倒是可以
      

  5.   

    楼主试试如下的一个函数:
    private string ExecuteCSharpCode(string code)
    {
    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();
    cp.ReferencedAssemblies.Add("System.dll");
    cp.ReferencedAssemblies.Add("System.Drawing.dll");
    cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
    cp.GenerateExecutable = false;
    cp.OutputAssembly = null;
    cp.GenerateInMemory = true; string source =
    "using System;\n" +
    "using System.Drawing;\n" +
    "using System.Windows.Forms;\n" +
    "namespace Samples {\n" +
    " public class ExecuteCode {\n" +
    " public void Execute() {\n" +
    " " + code + ";\n" +
    " }\n" +
    " }\n" +
    "}";
    string strResult = null;
    CompilerResults cr = provider.CompileAssemblyFromSource(cp, source);
    if (cr.Errors.Count > 0)
    {
    strResult += string.Format("Errors building \r\n{0}", source);
    strResult += "\r\n"; foreach (CompilerError ce in cr.Errors)
    {
    strResult += "(" + ce.ErrorNumber + ")" + ce.ErrorText;
    strResult += "\r\n";
    }
    return strResult;
    } try
    {
    Type[] types = cr.CompiledAssembly.GetTypes();
    if (types != null && types.Length > 0)
    {
    Type type = types[0];
    if (type != null)
    {
    object obj = cr.CompiledAssembly.CreateInstance(type.FullName);
    MethodInfo mi = type.GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
    if (mi != null)
    {
    object tmpRet = mi.Invoke(obj, null);
    if (tmpRet != null)
    {
    strResult = tmpRet.ToString();
    }
    }
    }
    } strResult += "\r\n";
    }
    catch (Exception ex)
    {
    strResult += ex.Message;
    strResult += "\r\n";
    }
    return strResult;
    }
      

  6.   

    例如如下的调用显示一个MessageBox消息:ExecuteCSharpCode("MessageBox.Show("aaa"));