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

本文介绍了一种在.NET中执行字符串的方法,通过反射调用指定方法,并传递参数。该方法适用于简单的字符串命令执行场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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
代码已测试通过。

转载于:https://www.cnblogs.com/Lewis/archive/2008/03/23/1118978.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值