Microsoft.CodeAnalysis 入门
1 安装 Microsoft.CodeAnalysis
我这里创建的是WPF的项目,首先再VS2015中用NuGet控制台进行安装
Install-Package Microsoft.CodeAnalysis
Install-Package Microsoft.CodeAnalysis.CSharp.Scripting
2 using 添加
1 using Microsoft.CodeAnalysis.Scripting; 2 using Microsoft.CodeAnalysis.CSharp.Scripting; 3 using Microsoft.CodeAnalysis.CSharp; 4 using Microsoft.CodeAnalysis.CSharp.Syntax;
3 Hello World
1 #region 01 Hello world 2 //Hello Rolysn 3 Console.WriteLine(CSharpScript.RunAsync( 4 @"string ret =""Hello Rolysn"";") 5 .Result.GetVariable("ret").Value); 6 7 #endregion
4 引用和命名空间
1 #region 02 References and Namespaces 2 ScriptOptions scriptOptions = ScriptOptions.Default; 3 #region 引用配置 4 //Add reference to mscorlib 5 var mscorlib = typeof(System.Object).Assembly; 6 var systemCore = typeof(System.Linq.Enumerable).Assembly; 7 scriptOptions = scriptOptions.AddReferences(mscorlib); 8 scriptOptions = scriptOptions.AddReferences(systemCore); 9 scriptOptions = scriptOptions.AddImports("System", "System.Linq", "System.Collections.Generic"); 10 #endregion 11 var state = CSharpScript.RunAsync(@"int x=2;int y=3;int z =x*y;return z+1;"); 12 //int x=2 => 2 13 string x = state.Result.GetVariable("x").Value.ToString(); 14 //return return z+1 => 7 15 string retvalue = state.Result.ReturnValue.ToString(); 16 //Int32 17 Type xtype = state.Result.GetVariable("x").Value.GetType(); 18 if(xtype.FullName == typeof(int).FullName) 19 { 20 21 } 22 //int z =x*y => 6 23 string z =state.Result.GetVariable("z").Value.ToString(); 24 25 string sourceCode = state.Result.Script.Code; 26 27 string output = ""; 28 foreach (var p in state.Result.Variables) 29 { 30 output += string.Format("name:{0},type:{1},value:{2};", p.Name, p.Type, p.Value); 31 } 32 Console.WriteLine(output); 33 #endregion
1 #region 03 SyntaxTree 2 var tree = CSharpSyntaxTree.ParseText(@" 3 public class MyClass 4 { 5 public int FnSum(int x,int y) 6 { 7 return x+y; 8 } 9 }"); 10 11 var syntaxRoot = tree.GetRoot(); 12 var MyClass = syntaxRoot.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); 13 var MyMethod = syntaxRoot.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); 14 15 Console.WriteLine(MyClass.Identifier.ToString()); 16 Console.WriteLine(MyMethod.Identifier.ToString()); 17 Console.WriteLine(MyMethod.ParameterList.ToString()); 18 #endregion
5 宿主对象交互
1 #region 04 Globals 2 3 var state4 = CSharpScript.RunAsync(@"var ret = requestData + "" from globals""; ", globals: new Globals { requestData = "hello world" }); 4 Console.WriteLine( state4.Result.GetVariable("ret").Value); 5 6 #endregion
1 public class Globals 2 { 3 /// <summary> 4 /// 可以在脚本中直接进行调用 5 /// </summary> 6 public string requestData { get; set; } 7 8 }
水平有限,望各位园友不吝赐教!如果觉得不错,请点击推荐和关注!
出处:http://www.cnblogs.com/isaboy/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/isaboy/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。