Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Roslyn Compiler Service

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how to use the Roslyn compiler service, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

One of the important features of the compiler Roslyn in .NET Core and C # 6x7 in .NET 4.6 is "Compiler as a Service". To put it simply, it is to open the compiler to a service that can be called in code. Usually, a function is needed in a workflow engine or rules engine to evaluate expressions. Before Roslyn, I used to rely on Antlr [Antlr (abbreviation for "another language recognition tool"), a library originally written in Java to build complex parser code based on special grammars (grammars). It is like an enhanced version of regular expression for language parsing. You can write syntax rules for a language, and Antlr will generate code for you. Based on Antlr, there is a lightweight C # compiler service Expression Evaluator.

To execute a C # script using Roslyn in your own code, first do the following steps of preparation.

1. Install Microsoft.CodeAnalysis.CSharp.Scripting through Nuget

2. Add a reference to the following namespace to the code.

Using Microsoft.CodeAnalysis.CSharp.Scripting

Using Microsoft.CodeAnalysis.Scripting

Classic HelloWorld

First of all, let's start with the classic Hello World to show how to execute a script.

Static void Main (string [] args)

{

Var options =

ScriptOptions.Default

.AddReferences ("System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

Var bar = new Bar () {StaffId = 5686, UnitId = 2, Age = 15}

Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync ("System.Console.WriteLine (\" hello world\ ");", options)

}

As you can see from the above code, it's relatively easy to execute a script, you can execute your own script through the Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync () function, and it's easy if we want to get the return value of the script.

Var scriptState = CSharpScript.RunAsync ("3 / 2 / 5", ScriptOptions.Default)

Console.WriteLine (scriptState)

Execute a script in a session

A lot of times, we can't execute all the scripts at once, but enter and execute one sentence at a time as we do in shell. If we execute the following code

Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync ("var I = 3;")

Var result = Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync ("I * 2")

What we get is not the result we want, 6, but an exception:

The reason for this is that the CSharpScript.RunAsync function is executed in a separate context each time and is not associated with the previous statement. If we are going to create a script in the CSharpScript.Create () function, run it through the function ContinueWith to form a complete script. The correct way is as follows:

Var S0 = CSharpScript.Create ("int x = 1;")

Var S1 = s0.ContinueWith ("int y = 2;")

Var S2 = s1.ContinueWith ("x + y")

Console.WriteLine (s2.RunAsync () .Result.ReturnValue)

Share data in scripts and programs

When we execute a script, in addition to getting the output of the script, we often need to set the input of the script, and there are many ways to set the input. The most direct way to splice scripts, but the efficiency and maintainability of doing so is very poor. In addition, we can also use the traditional IPC communication mechanism-file, Socket and so on, which is more troublesome on the one hand, and also involves serialization for complex objects, which is also very inconvenient.

Roslyn provides a simpler and more efficient solution: a host object is passed in the session, and the script in the session can also access the member variables of the host object.

Namespace RoslynCosonle

{

Class Program

{

Static void Main (string [] args)

{

Var options =

ScriptOptions.Default

.AddReferences ("System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

Var S0 = CSharpScript.Create ("int x = 1;")

Var S1 = s0.ContinueWith ("int y = 2;")

Var S2 = s1.ContinueWith ("x + y")

Console.WriteLine (s2.RunAsync () .Result.ReturnValue)

Var bar = new Bar () {StaffId = 5686, UnitId = 2, Age = 15}

Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync ("System.Console.WriteLine ((StaffId==5686 & & UnitId==2) | | (UnitId== 3 | | Age > 10));", options, bar)

}

}

Public class Bar

{

Public string Foo = > "Hello World!"

Public int StaffId {get; set;}

Public int UnitId {get; set;}

Public int Age {get; set;}

}

The input grasped by the object Bar is passed to the expression, and then the expression can evaluate the result, which is the expression evaluation we want in the workflow engine.

The above is how to use the Roslyn compiler service, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report