使用CSharpScript创建一个函数并执行它

时间:2017-10-02 11:12:26

标签: c# .net

是否可以将函数定义为脚本然后运行它?

我试图做出类似的事情:

//defined in a namespace
public class Params{public string input { get; set; }}


string script = "string TryToUpper(string input){ return input.ToUpper(); }";
var v = CSharpScript.Create(script,  globalsType: typeof(Params) );

// what to do to execute TryToUpper and get "GIUSEPPE" back?
var val = v.RunAsync(???);

1 个答案:

答案 0 :(得分:2)

你必须在该脚本中做两件事:首先,定义函数,然后实际运行它并返回它的结果。像这样:

public class Params
{
    public string input;
}

Params globals = new Params();
globals.input = "some lowercase text";

string script = "string TryUpper(string str) { return str.ToUpper(); } return TryUpper(input);";

string result = await CSharpScript.EvaluateAsync<string>(script, globals: globals);