C#新手
嗨。这是对CS-Script 3.28.7,添加脚本到C#的测试.我需要实现非常简单的函数,这些函数稍后将从cfg文件中读取。
我查看了文档,但是没有找到读取外部类和静态vars的方法。我得到了values和rnd的消息the name XXX is not available in this context。
我忘了什么?
using System;
using CSScriptLibrary;
namespace EmbedCS
{
class Program
{
public static int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
static Random rnd = new Random();
static void Main(string[] args)
{
ExecuteTest();
Console.Read();
}
private static void ExecuteTest()
{
bool result;
var scriptFunction = CSScript.CreateFunc<bool>(@"
bool func() {
int a = rnd.Next(10);
int b = rnd.Next(10);
return values[a] > values[b];
}
");
result = (bool)scriptFunction();
Console.Read();
}
}
}发布于 2019-04-11 08:50:27
这个应该能用
using System;
using CSScriptLibrary;
namespace EmbedCS
{
public class Program
{
public static int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
public static Random rnd = new Random();
static void Main(string[] args)
{
ExecuteTest();
Console.Read();
}
private static void ExecuteTest()
{
bool result;
var scriptFunction = CSScript.CreateFunc<bool>(@"
bool func() {
int a = EmbedCS.Program.rnd.Next(10);
int b = EmbedCS.Program.rnd.Next(10);
return EmbedCS.Program.values[a] > EmbedCS.Program.values[b];
}
");
result = (bool)scriptFunction();
Console.Read();
}
}
}记住,在C#中,一切都是如此的含蓄。
您的func()不是Program的成员。因此他们无法识别Program中的字段。
一些动态语言在语言级别上具有绑定上下文(如ruby的binding),因此库可以执行黑魔法操作。但不是在C#。
https://stackoverflow.com/questions/55627113
复制相似问题