这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
public int xx = 1; // variable I want to access from the runtime code
static void Main(string[] args)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode());
var cls = results.CompiledAssembly.GetType("ConsoleApplication1.Program");
var method = cls.GetMethod("DynamicMethod", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, null);
int a = int.Parse(Console.ReadLine()); // pause console
}
static string[] GetCode()
{
return new string[]
{
@"using System;
namespace ConsoleApplication1
{
class Program
{
public static void DynamicMethod()
{
Console.WriteLine(""Hello, world!"");
}
}
}"
};
}
}
}
我想知道是否可以从运行时代码中访问变量int xx(例如,将xx=2;行放在"hello world"之后)。那太棒了感谢:)
是的,您可以使用它,但您需要:
- 添加对包含
xx
的程序集的引用(为了方便起见,我将此程序集称为StaticAssembly
,因此它可能是正在运行的控制台exeStaticAssembly.exe
) - 使
StaticAssembly
中的Program
为public
类型,使其可访问 - 要么将
xx
变成static
字段,要么实例化Program
的实例并以某种方式将其传递给动态代码
例如,以下方法有效(我使用的是"实例化实例并传递它"的方法,因此我为DynamicMethod
添加了一个参数):
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace StaticAssembly
{
public class Program
{
public int xx = 1; // variable I want to access from the runtime code
static void Main(string[] args)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("StaticAssembly.exe");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode());
var cls = results.CompiledAssembly.GetType("GeneratedAssembly.Program");
var method = cls.GetMethod("DynamicMethod", BindingFlags.Static | BindingFlags.Public);
var p = new Program();
p.xx = 42;
method.Invoke(null, new object[] {p});
int a = int.Parse(Console.ReadLine()); // pause console
}
static string[] GetCode()
{
return new string[]
{
@"using System;
namespace GeneratedAssembly
{
class Program
{
public static void DynamicMethod(StaticAssembly.Program p)
{
Console.WriteLine(p.xx);
Console.WriteLine(""Hello, world!"");
}
}
}"
};
}
}
}