C# 和 CS-Script:不在上下文中的变量

C# and CS-Script: variables not in context

[C# 新手]

嗨。这是 CS-Script 3.28.7 的测试,将脚本添加到 C#。 我需要实现非常简单的功能,这些功能稍后会从 cfg 文件中读取。

我浏览了文档,但是没有找到读取外部类和静态变量的方法。我得到 valuesrnd 消息 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();
        }
    }
}

这个应该有用

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# 中。