【发布时间】:2015-08-23 10:33:46
【问题描述】:
我尝试使用 CompileAssemblyFromSource 在我的主类中更改 1 个值。 但是当我编译时出现错误“无法加载文件或程序集或其依赖项之一”,这只发生在我尝试更改其他类的静态值时。但是,如果我从这个 FooClass 返回一些输出或在控制台上写任何东西,那么一切都很好。但是如何更改其他类的值?
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace stringToCode
{
class Program
{
public static int q = 0;
static void Main(string[] args)
{
string source = "namespace stringToCode { public class FooClass { public void Execute() { Program.q = 1; } } }";
Console.WriteLine("q=" + q);
using (var foo = new CSharpCodeProvider())
{
var parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
string location = assembly.Location;
if (!String.IsNullOrEmpty(location))
{
parameters.ReferencedAssemblies.Add(location);
}
}
catch (NotSupportedException)
{}
}
var res = foo.CompileAssemblyFromSource(parameters ,source);
var type = res.CompiledAssembly.GetType("FooClass"); //<- here i has error
var obj = Activator.CreateInstance(type);
var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
Console.WriteLine("q=" + q);
Console.ReadLine();
}
}
}
}
【问题讨论】:
-
试试
GetType("stringToCode.FooClass")。此外,Program是内部的,除非您向主程序集添加一些属性或将其公开,否则它将不起作用。 -
这有帮助!谢谢!
标签: c# compileassemblyfromsource