oleg-shilo / cs-script

C# scripting platform
http://www.cs-script.net
MIT License
1.56k stars 234 forks source link

how to use this to run csharp string as script in netapp #333

Closed heartacker closed 1 year ago

heartacker commented 1 year ago

for example: code:

 using System;
 using ns = My.other.NameSpce.Foo;// the net app

 public class Script
 {
      public int Sum(int a, int b)
      {
          return a+b;
      }
 }

 var s = new Script();
 var result = s.Sum(2, 3);
 Console.WriteLine(result);

 System.Console.WriteLine(ns.Bar(result));// call the bar functions  of the host net app

 System.Console.WriteLine("The code run end");

I want to run the code(string) in my net app by using CSScript. how can we?

is there any API like CSScript.Evaluator.Run(string codestring) for us to evaluate thanks

heartacker commented 1 year ago

https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md

oleg-shilo commented 1 year ago

The example above is not using CS-Scriprt but Roslyn API. But I assume your question was about CS-Script (since it is CS-Script project page). 😄 If it is correct then have a look at the corresponding Wiki: https://github.com/oleg-shilo/cs-script/wiki/Hosted-Script-Execution

This is the simplest possible sample from it:

dynamic calc = CSScript.Evaluator
                       .LoadMethod(@"int Multiply(int a, int b)
                                     {
                                         return a * b;
                                     }");

int result = calc.Multiply(3, 2);

If you add CS-Script nuget package to your VS project, it will also add the samples file to it.

heartacker commented 1 year ago

no, your example is only the method, I also need to run the method in the script I want to run this

 using System;
 using ns = My.other.NameSpce.Foo;// the net app

 public class Script
 {
      public int Sum(int a, int b)
      {
          return a+b;
      }
 }

 var s = new Script();
 var result = s.Sum(2, 3);
 Console.WriteLine(result);

 System.Console.WriteLine(ns.Bar(result));// call the bar functions  of the host net app

 System.Console.WriteLine("The code run end");

with one API,

oleg-shilo commented 1 year ago

Please read the Wiki that I provided the link for. As I indicated I only gave you the simplest example and the article contains plenty of others.

And if you do use the nuget package I suggested it will bring all other possible samples.

You can also browse some of the samples in the repo: image