使用Roslyn引用PCL库会导致.NET版本问题

时间:2015-11-26 02:43:13

标签: c# .net portable-class-library roslyn

我正在尝试使用Roslyn来执行引用PCL库的代码块。我的控制台应用程序和PCL库都针对.NET 4.5

语法树在引用的库中执行构造库类的方法。应该没有.NET 4.0引用。

(5,27):错误CS0012:类型“对象”在未引用的程序集中定义。您必须添加对程序集'System.Runtime,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'的引用。

有没有人与PCL和Roslyn有过问题,或者之前有过这个问题?

MyCompanyApplication:Program.cs中

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Reflection;

namespace MyCompanyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      EmitResult Result;
      var Options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

      CSharpCompilation Compilation = CSharpCompilation.Create(
          assemblyName: Path.GetRandomFileName(),
          syntaxTrees: new[] { CSharpSyntaxTree.ParseText(
@"class Test
{
  public void Run(MyCompanyLibrary.Class Class)
  {
    var Label = Class.NewLabel();
  }
}") },
          references: new[] 
          {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            MetadataReference.CreateFromFile(typeof(MyCompanyLibrary.Class).Assembly.Location),
          },
          options: Options);

      Assembly Assembly = null;
      using (var Stream = new MemoryStream())
      {
        Result = Compilation.Emit(Stream);

        if (Result.Success)
          Assembly = Assembly.Load(Stream.GetBuffer());
      }

      if (Result.Success)
      {
        var TestType = Assembly.GetType("Test");
        var Instance = TestType.GetConstructor(new Type[0]).Invoke(new object[0]);
        var RunMethod = TestType.GetMethod("Run");

        RunMethod.Invoke(Instance, new object[] { new MyCompanyLibrary.Class() });
      }
      else
      {
        Console.WriteLine("Test (PCL) failed");
        Console.ReadLine();
      }
    }
  }
}

class Test
{
  public void Run(MyCompanyLibrary.Class Class)
  {
    var Label = Class.NewLabel();
  }
}

MyCompanyLibrary:Class.cs

namespace MyCompanyLibrary
{
  public class Class
  {
    public Class()
    {
    }

    public Label NewLabel()
    {
      return new Label(this);
    }
  }

  public class Label
  {
    internal Label(Class Class)
    {
      this.Class = Class;
    }

    private Class Class;
  }
}

Solution References

1 个答案:

答案 0 :(得分:2)

您正在从" MyCompanyApplication"中添加对object的引用,该引用不是可移植类库。

改变这个:

MetadataReference.CreateFromFile(typeof(object).Assembly.Location)

到此:

MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile7\System.Runtime.dll")