C # create an instance of an object from a string

I have a string variable:

string classCode = "public class Person { public string Name{get;set;} }";

How to instantiate an object from a class? as

object obj = CreateAnInstanceAnObject(classCode);
+3
source share
4 answers

You will need to use CodeDom to compile the assembly in memory, and then use reflection to create the type.

Here's a sample article on MSDN that goes through code generation .

After you compiled the code, you can use Activator.CreateInstance to instantiate it.

+6
source

, , :

namespace DynamicCompilation
{
    using System;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Reflection;

    using Microsoft.CSharp;

    internal static class Program
    {
        private static void Main()
        {
            var ccu = new CodeCompileUnit();
            var cns = new CodeNamespace("Aesop.Demo");

            cns.Imports.Add(new CodeNamespaceImport("System"));

            var ctd = new CodeTypeDeclaration("Test")
            {
                TypeAttributes = TypeAttributes.Public
            };
            var ctre = new CodeTypeReferenceExpression("Console");
            var cmie = new CodeMethodInvokeExpression(ctre, "WriteLine", new CodePrimitiveExpression("Hello World!"));
            var cmm = new CodeMemberMethod
            {
                Name = "Hello",
                Attributes = MemberAttributes.Public
            };

            cmm.Statements.Add(cmie);
            ctd.Members.Add(cmm);
            cns.Types.Add(ctd);
            ccu.Namespaces.Add(cns);

            var provider = new CSharpCodeProvider();
            var parameters = new CompilerParameters
            {
                CompilerOptions = "/target:library /optimize",
                GenerateExecutable = false,
                GenerateInMemory = true
            };

            ////parameters.ReferencedAssemblies.Add("System.dll");

            var results = provider.CompileAssemblyFromDom(parameters, ccu);

            if (results.Errors.Count == 0)
            {
                var t = results.CompiledAssembly.GetType("Aesop.Demo.Test");
                var inst = results.CompiledAssembly.CreateInstance("Aesop.Demo.Test");
                t.InvokeMember("Hello", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, inst, null);
            }

            Console.ReadLine();
        }
    }
}
+3

, , . Activator.CreateInstance.

, , . 1) , 2) . , , #. , StackOverflow.

+1

, :

RunTime

, , . , .

What are you trying to accomplish by creating this object?

0
source

Source: https://habr.com/ru/post/1727658/


All Articles