1
我有一个运行时编译类的问题。我有这样的事情2类:在编译文件中编译类
一流
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program.Bullet {
public class Class1{
private int i;
public Class1(int j){
i=j;
}
}
}
和第二类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Program.Bullet;
namespace Program.Object {
public class Class2{
public Class2(){
Class1 c1 = new Class1(5);
}
}
}
这两个班,我想在运行时编译和在我的项目中使用它们。所以,我有函数编译(XmlNode的大约有FULLPATH等数据):
private ModuleBuilder moduleBuilder;
private List<string> isCompiled;
private void Compile(XmlNode compileingClasses) {
foreach (XmlNode compileingClass in compileingClasses) {
string fullPath = compileingClass.Attributes["path"].InnerText;
string type = compileingClass.Attributes["name"].InnerText; ;
if (!isCompiled.Contains(type)) {
isCompiled.Add(type);
var syntaxTree = SyntaxTree.ParseFile("../../File1/File2/" + fullPath);
var comp = Compilation.Create("Test.dll"
, syntaxTrees: new[] { syntaxTree }
, references: metadataRef
, options: comilationOption
);
// Runtime compilation and check errors
var result = comp.Emit(moduleBuilder);
if (!result.Success) {
foreach (var d in result.Diagnostics) {
Console.WriteLine(d);
}
throw new XmlLoadException("Class not found " + fullPath);
}
}
}
}
是否有可能得到的Class1的参考CLASS2?
编辑:更好的问题
是否有可能创建编译Class1
MetadataReference?
喜欢的东西:
string fullName = bullet.Attributes["fullName"].InnerText;
var o = moduleBuilder.GetType(fullName);
metadataRef.Add(new MetadataFileReference(o.Assembly.Location));
这掷NotSupportedException
这两个类都不在解决方案中,它们位于不同的文件中。我的想法是将'moduleBuilder'的引用添加到'metedateRef',但我不知道如何。 – wolen
通常,向同一个程序集添加引用是没有意义的。不确定它是如何在同一个装配中遇到多种复杂问题的。你不能在同一个'Compilation'中生成这两个类吗? – svick
我重新设计了一些函数来将所有的syntaxTrees合并到一个编译中,并且它可以工作。谢谢你,你救了我一些不眠之夜。 – wolen