In the following snippet, how do I pass my object as parameter to the method in the script?
var c = new MyAssembly.MyClass()
{
Description = "test"
};
var code = "using MyAssembly;" +
"public class TestClass {" +
" public bool HelloWorld(MyClass c) {" +
" return c == null;" +
" }" +
"}";
var script = CSharpScript.Create(code, options, typeof(MyAssembly.MyClass));
var call = await script.ContinueWith<int>("new TestClass().HelloWorld()", options).RunAsync(c);
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.
The Globals
type should hold any global variable declarations as it's properties.
Assuming you got the correct references for your script:
var metadata = MetadataReference.CreateFromFile(typeof(MyClass).Assembly.Location);
Option 1
You need to define a global var of type MyClass:
public class Globals
{
public MyClass C { get; set; }
}
And use that as a Globals
type:
var script =
await CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata),
globalsType: typeof(Globals))
.ContinueWith("new TestClass().HelloWorld(C)")
.RunAsync(new Globals { C = c });
var output = script.ReturnValue;
Note that in the ContinueWith
expression the is a C
variable as well as a C
property in Globals
. That should do the trick.
Option 2
In your case it might make sense to create a delegate if you intend to call the script multiple times:
var f =
CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata),
globalsType: typeof(Globals))
.ContinueWith("new TestClass().HelloWorld(C)")
.CreateDelegate();
var output = await f(new Globals { C = c });
Option 3
In your case you don't even need to pass any Globals
var f =
await CSharpScript.Create(
code: code,
options: ScriptOptions.Default.WithReferences(metadata))
.ContinueWith<Func<MyClass, bool>>("new TestClass().HelloWorld")
.CreateDelegate()
.Invoke();
var output = f(c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With