Build your own C # script with Roslyn

Source: Internet
Author: User
Tags microsoft website

Build your own C # script with Roslyn

In the next generation of C #, an important feature is the "Compiler as a service", which simply means that the compiler is opened up to one that can be invoked in code. Recently used the Microsoft release of the Project Roslyn CTP version, feeling is very powerful.

To execute a C # script in your own code, start with the following steps.

    1. Download the Roslyn CTP version and install it on the Microsoft website
    2. Add references to Roslyn.Compilers.dll and Roslyn.Compilers.CSharp.dll in the project
    3. Add a reference to the following namespace in your code.
      Using Roslyn.scripting;
      Using Roslyn.Scripting.CSharp;

The classic HelloWorld

Let's start with the classic Hello world to get started on how to execute a script.

static void Main (string[] args)
{
var scriptengine = new ScriptEngine ();
Scriptengine.execute ("System.Console.WriteLine (\" Hello world\ ")");
}

As you can see from the code above, executing a script is relatively straightforward, as long as you create a ScriptEngine object, and then you can execute your own script through the Scriptengine.execute () function.

It is also easy if we want to get the return value of the script.

var result = scriptengine.execute<int> ("3+2*5");
Console.WriteLine (result);

Executing scripts in a session

Many times, we cannot execute all the scripts at once, but instead enter a sentence as in the shell. If we execute the following code:

var scriptengine = new ScriptEngine ();
Scriptengine.execute ("var i = 3;");
var result = Scriptengine.execute ("I * 2");

What we get is not the result we want 6, but an exception: (a): Error cs0103:the name ' I ' does not exist in the current context.

The reason for this is that the Scriptengine.execute () function is executed each time in a separate context and is not associated with the preceding statement. If we want to add the session parameter to the Scriptengine.execute () function to indicate that it is in the same session. The correct way is as follows:

var scriptengine = new ScriptEngine ();
var session = Session.create ();
Scriptengine.execute ("var i = 3;", session);
var result = Scriptengine.execute ("I * 2", session);

Sharing data in scripts and programs

When we execute the script, in addition to get the output of the script, many times we need to set the script input, there are many ways to set the input. The most straightforward way to stitch scripts but the efficiency and maintainability of doing so is very poor. Also can through the traditional IPC communication mechanism-file, socket, and so on, this way is more troublesome, and for complex objects, but also involves serialization, is very inconvenient.

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

Let's give a simple example:

Namespace Host
{
public class Hostobject
{
public string state = "Hello";
}
}

Class Program
{
static void Main (string[] args)
{
var hostreference = new Roslyn.Compilers.AssemblyFileReference (typeof (Host.hostobject). Assembly.location);
var engine = new ScriptEngine (references:new[] {hostreference}, importednamespaces:new[] {"System"});
var host = new Host.hostobject ();
var session = Session.create (host);

var result = engine. Execute<string> ("State + state", session);
Console.WriteLine (result);

Host. State = "Go Go hello";
result = engine. Execute<string> ("State + state", session);
Console.WriteLine (result);
}
}

This first creates a host object of type Hostobject, and it creates a session. This embeds the member variable state of the host object in the script, and the state variable can be shared in both the script and the program.

Build your own C # script with Roslyn

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.