0

i'm trying to generate Code at runtime which uses a custom class from another Namespace.

Here´s my code:

namespace Test.Programm.Network
{
    class Handler
    {
        public void CreateAssembly()
        {
            string[] code =
            {
                @"using System;
                using System.Collections;


                namespace Test.Programm.Network
                {
                    class HandleMessage 
                    {
                        protected static internal Queue _queue;  
                        public static void Received(string message) 
                        {
                            lock (_queue)
                            { 
                                _queue.Enqueue(message);
                            }
                        } 
                        public HandleMessage() 
                        {
                            _queue = new Queue(); 
                        } 
                    }
                }"
            };

            CompilerParameters parms = new CompilerParameters();

            parms.GenerateExecutable = false;
            parms.GenerateInMemory = true;
            CodeDomProvider compiler = null;
            compiler = CodeDomProvider.CreateProvider("CSharp");

            CompilerResults compilerResults = compiler.CompileAssemblyFromSource(parms, code);
            var cls = compilerResults.CompiledAssembly.GetType("Test.Programm.Network.HandleMessage");

            Assembly assembly = compilerResults.CompiledAssembly;

            var newHandler = assembly.CreateInstance(compilerResults.CompiledAssembly.GetType("Test.Programm.Network.HandleMessage").ToString());
        }
    }

}

But i don´t want to pass a string to my function, i want to pass an own type to that function.

Now i have a simple message class like that:

namespace Test.Programm.Messages
{
    public class Message<T>
    {
        string _message;
    }
}

if i want too add a using Test.Programm.Messages to the code i want to generate, i´m getting error that this Namespace doesn´t exist, missing reference...

I tried to add parms.ReferencedAssemblies.Add("Grid.Node.Messages"); to the code Generation, but this doesnt work. searching the web and SO haven´t given an answer yet -.-

Thanks for your help.

4

1 回答 1

0

您应该引用程序集而不是命名空间。像这样的东西:

parms.ReferencedAssemblies.Add("path_to.dll");

wherepath_to.dll是包含 type 的程序集文件的路径Message<T>

于 2013-05-28T09:14:26.537 回答