ICodeCompiler comp = new CSharpCodeProvider().CreateCompiler();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
StringBuilder codes = new StringBuilder();
codes.Append("using System; \n");
codes.Append("using System.Data; \n");
codes.Append("namespace Test \n");
codes.Append("{ \n");
codes.Append(" public class TestClass \n");
codes.Append(" { \n");
codes.Append(" public static string TestMethod() \n");
codes.Append(" { \n");
codes.Append(" return ""; \n");
codes.Append(" } \n");
codes.Append(" } \n");
codes.Append("} \n");
CompilerResults cr = comp.CompileAssemblyFromSource(cp, codes.ToString());
after I compiled this class succesfully and used the method by invoke method successfully, I used GetType("Test.TestClass") then return null. what's wrong?
Type.GetType
needs an AssemblyQualifiedName
to work. However, your compiled assembly has a random name.
Options for you to get the Type are:
cr.CompiledAssembly.GetType
cr.CompiledAssembly.ExportedTypes
cp.OutputAssembly =@"C:\my_full_path\myName.dll"
then use Test.TestClass, myName, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.