.net中怎样执行一个字符串

在javascript中执行字符串很简单,eval方法就可以了。但在.NET中怎么实现呢?
代码如下:

 1using System;
 2using System.Reflection;
 3
 4
 5namespace 执行字符串
 6{
 7    /// <summary>
 8    /// Class1 的摘要说明。
 9    /// </summary>

10    class Class1
11    {
12        /// <summary>
13        /// 应用程序的主入口点。
14        /// </summary>

15        [STAThread]
16        static void Main(string[] args)
17        {
18            
19            string test = "MyProc(10)";
20            string name = test.Substring(0, test.IndexOf('('));
21            string arg = test.Replace(name + "(""").TrimEnd(')');
22
23            MethodInfo mi = typeof(Class1).GetMethod(name);
24            if (mi != null)
25            {
26                object[] os = new object[] { Convert.ToInt16(arg) };
27                mi.Invoke(null, os);
28            }

29
30
31        }

32
33        public static void MyProc(int n)
34        {
35            Console.Write(n);
36            Console.WriteLine("");
37        }

38
39
40    }

41}

42
代码已测试通过。
posted @ 2008-03-23 23:51  Ricebug  阅读(451)  评论(4编辑  收藏  举报