【发布时间】:2018-07-11 15:43:15
【问题描述】:
我正在使用 Roslyn 为具有定义的业务对象(比如说,Customer)生成 Linq 表达式
public class Customer
{
public List<Order> Orders { get; set; }
}
编译 C# code 的 Roslyn 代码是 -
var linqType = typeof(System.Linq.Enumerable);
List<MetadataReference> metadataReferences = new List<MetadataReference>()
{
//Other business DLLs as well
MetadataReference.CreateFromFile(linqType.Assembly.Location)
};
//mscorlib
car dlls = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES").ToString().Split(new char[] { ';' });
foreach (var platformDLL in dlls)
{
metadataReferences.Add(MetadataReference.CreateFromFile(platformDLL));
}
// Removed: Get Units
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Debug,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
allowUnsafe: true);
compilationOptions.WithUsings(GetNamespaces());
var compilation = CSharpCompilation.Create(assemblyName: "customer",
syntaxTrees: units.Select(x => x.SyntaxTree).ToArray(),
references: metadataReferences,
options: compilationOptions);
生成的 Linq 表达式如下。
Exists<Customer>(f => f.Orders.Any() == true)
该类也有以下使用
using System;
using System.Text;
using System.Linq;
但是,我仍然遇到错误
error CS1061: 'Customer' does not contain a definition for 'Orders.Any()' and no extension method 'Orders.Any()' accepting a first argument of type 'Customer' could be found (are you missing a using directive or an assembly reference?)
代码生成正确,但使用 Roslyn 编译代码失败并出现上述错误。当我在 Visual Studio 中复制粘贴生成的代码时,编译时没有错误
【问题讨论】:
-
目前尚不清楚这是代码生成问题还是编译问题。如果只是输出代码,是否可以正常构建?
-
正确输出代码,但编译失败
-
那么如果你将代码输出到一个文件并用csc编译它,那行得通吗? (顺便说一句,minimal reproducible example 会更容易帮助你。)