c#如何将字符串转化成代码
1、方案一、
通过拼接字符串的方式,生成一个cs类文件,再使用反射的方式调用此cs文件即可,此方式最简单,只需要熟练使用反射的相关知识即可。
2、方案二、
使用CSharpCodeProvider对象来解析字符串并通过反射的方式执行。
上面两种方案都需要熟练使用反射的技术,方案一相对来说比较简单,这里主要学习使用方案二来是实现相关功能。
3、按照此方法完成需要进行以下几个步骤
1、//1.创建CSharpCodeProvider的实例
CSharpCodeProvider cs = new CSharpCodeProvider();
2、//2.创建一个ICodeComplier对象
ICodeCompiler cc = cs.CreateCompiler();
3、//3.创建一个CompilerParameters的实例
CompilerParameters cp = new CompilerParameters();
cp.GenerateInMemory = true;//设定在内存中创建程序集
cp.GenerateExecutable = false;//设定是否创建可执行文件,也就是exe文件或者dll文件
cp.ReferencedAssemblies.Add("System.dll");//此处代码是添加对应dll文件的引用
cp.ReferencedAssemblies.Add("System.Core.dll");//System.Linq存在于System.Core.dll文件中
4、//4.创建CompilerResults的实例
string strExpre= "using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DynamicCompileTest{public class TestClass1{public bool CheckBool(string source){ return source.Contains(\"SC\"); }}}";
CompilerResults cr = cc.CompileAssemblyFromSource(cp, strExpre);
if (cr.Errors.HasErrors)
{
Console.WriteLine(cr.Errors.ToString());
}
else
{
//5.创建一个Assembly对象
Assembly ass = cr.CompiledAssembly;//动态编译程序集
object obj = ass.CreateInstance("DynamicCompileTest.TestClass1");
MethodInfo mi = obj.GetType().GetMethod("CheckBool");
bool result = (bool)mi.Invoke(obj, new object[] { "LYF" });
}
Console.ReadKey();