zoukankan      html  css  js  c++  java
  • C# 动态编译并动态传入对象

    创建对象并执行方法,传入一个动态对象作为参数

     static object DynamicCreateAssembly(dynamic inputObject)
            {
                Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                //
                System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
                compilerParameters.ReferencedAssemblies.Add("System.dll");
                compilerParameters.ReferencedAssemblies.Add("System.Linq.Expressions.dll");
                compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
                compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                compilerParameters.GenerateInMemory = true;
                //
                string source = @"
    using System;
    using System.Runtime.CompilerServices;
    public class Fuck {
        public static string FuckMe(dynamic input)
        {
            Console.WriteLine(input.Age);
            Console.WriteLine(input.Name);
            return ""okkkk"";
        }
    
    }
    ";
                var compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, source);
                if (compilerResults.Errors.Count > 0)
                {
                    foreach (var err in compilerResults.Errors)
                    {
                        Console.WriteLine(err);
                    }
                }
                var asm = compilerResults.CompiledAssembly.CreateInstance("Fuck");
                MethodInfo method = asm.GetType().GetMethod("FuckMe");
                return method.Invoke(asm, new object[] { inputObject });
            }
    

    需要传入的对象

     public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    

    调用

    static void Main(string[] args)
            {
                Person person = new Person();
                person.Name = "撒飞洒发撒";
    
                object result = DynamicCreateAssembly(person);
                Console.WriteLine($"返回值:{result}");
                Console.Read();
            }
    

  • 相关阅读:
    leetcode167 Two Sum II
    leetcode18 4Sum
    leetcode15 three sum
    leetcode-1-Two Sum
    SQL优化——select
    Hadoop 集群搭建
    虚拟机中的两台主机怎么相互拷贝文件
    doker5
    docker4
    docker3
  • 原文地址:https://www.cnblogs.com/trykle/p/14878492.html
Copyright © 2011-2022 走看看