0

[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();
        }
    }
}
4

1 回答 1

1

这个应该工作

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​​'s binding),因此库可以做黑魔法。但不是在 C# 中。

于 2019-04-11T08:50:27.537 回答