我正在开发一个程序资产生成系统,我希望它能够检测特定资产的源文件是否已更改,以便它只需要重新生成实际不同的资产。
一些谷歌搜索告诉我,没有办法使用简单的反射来获取类型的源文件,所以我试图想出一个解决方法。这就是我正在做的事情:
- 使用 Directory.GetFiles 获取项目目录中所有 .cs 文件的列表。
- 使用 CSharpCodeProvider.CompileAssemblyFromFile 将每个文件编译成自己的程序集。
- 如果compiledAssembly.GetType(targetType.FullName)存在,那么就是targetType的源文件。
问题是第 2 步给出了没有任何描述的编译错误:
- (0,0):错误:
- (0,0):错误:在(包装器托管到本机)System.Reflection.Assembly:GetTypes(布尔)
- (0,0):错误:在(包装器托管到本机)System.Reflection.Assembly:GetTypes(布尔)
- 等等
我认为这可能是因为当前程序集或应用程序域或任何已经包含它试图编译的确切类型,但这只是一个猜测。有谁知道可能导致这些错误的原因或我如何避免它们?
编辑:这是第 2 步的主要代码:
private static readonly CSharpCodeProvider CodeProvider = new CSharpCodeProvider();
private static readonly CompilerParameters CompilerOptions = new CompilerParameters();
static SourceInterpreter()
{
// We want a DLL in memory.
CompilerOptions.GenerateExecutable = false;
CompilerOptions.GenerateInMemory = true;
// Add references for UnityEngine and UnityEditor DLLs.
CompilerOptions.ReferencedAssemblies.Add(typeof(Application).Assembly.Location);
CompilerOptions.ReferencedAssemblies.Add(typeof(EditorApplication).Assembly.Location);
}
private static Assembly CompileCS(string filePath, out CompilerErrorCollection errors)
{
// Compile the assembly from the source script text.
CompilerResults result = CodeProvider.CompileAssemblyFromFile(CompilerOptions, filePath);
// Store any errors and warnings.
errors = result.Errors;
foreach (CompilerError e in errors)
{
if (!e.IsWarning) Debug.Log(e);
}
return result.CompiledAssembly;
}