简体   繁体   中英

why c# dynamic compiled type cannot be found by using Type.GetType method?

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:

  1. cr.CompiledAssembly.GetType
  2. cr.CompiledAssembly.ExportedTypes
  3. Give your assembly a name by adding
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM