创建对象并执行方法,传入一个动态对象作为参数
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();
}