2015-11-26 65 views
3

我正在嘗試使用Roslyn來執行引用PCL庫的代碼塊。我的控制檯應用程序和PCL庫都針對.NET 4.5使用Roslyn引用PCL庫導致.NET版本問題

語法樹在構建庫類的引用庫中執行一個方法。應該沒有.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

+0

您正在使用什麼版本的Visual Studio? –

+0

Microsoft Visual Studio Professional 2015 版本14.0.23107.0 D14REL Microsoft .NET Framework 版本4.6.00079 – Tristan

+0

從不*從GAC將程序集用作參考程序集。他們需要來自c:\ program files(x86)\ reference assembly。專門製作以隱藏各種4.x版本之間的差異。 Afaik您必須對路徑進行硬編碼,並希望機器安裝了正確的定位包。使用PCL庫是你在這裏不太喜歡的東西。 –

回答

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") 
+0

就是這樣,謝謝。 – Tristan

相關問題