• 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();
            }
    

  • 相关阅读:
    PHP静态
    PHP批量删除
    PHP增删改查
    PHP数据访问
    PHP继承和多态
    PHP封装
    PHP字符串处理和正则表达式
    PHP数组
    PHP函数
    PHP基础
  • 原文地址:https://www.cnblogs.com/trykle/p/14878492.html
Copyright © 2020-2023  润新知