访问以前编译的方法的 C# 脚本

本文关键字:方法 脚本 编译 访问 | 更新日期: 2023-09-27 18:00:05

我希望将我目前拥有的脚本解决方案转移到 C#,因为我相信这将解决我目前在不同平台上运行时面临的一些问题。我可以调用脚本中的函数并访问它们的变量,但是,我希望能够做的一件事是从脚本所在的类调用函数。有谁知道我该怎么做?

这是我目前用于调用和访问脚本中的对象的代码,但我希望能够从脚本中调用方法"Called",但不能:

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CSharp;
namespace scriptingTest
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            var csc = new CSharpCodeProvider ();
            var res = csc.CompileAssemblyFromSource (
                new CompilerParameters ()
                {
                    GenerateInMemory = true
                },
                @"using System; 
                    public class TestClass
                    { 
                        public int testvar = 5;
                        public string Execute() 
                        { 
                            return ""Executed."";
                        }
                    }"
            );
            if (res.Errors.Count == 0) {
                var type = res.CompiledAssembly.GetType ("TestClass");
                var obj = Activator.CreateInstance (type);
                var output = type.GetMethod ("Execute").Invoke (obj, new object[] { });
                Console.WriteLine (output.ToString ());
                FieldInfo test = type.GetField ("testvar");
                Console.WriteLine (type.GetField ("testvar").GetValue (obj));
            } else {
                foreach (var error in res.Errors)
                    Console.WriteLine(error.ToString());
            }
            Console.ReadLine ();
        }
        static void Called() // This is what I would like to be able to call
        {
            Console.WriteLine("Called from script.");
        }
    }
}

我正在尝试在 Mono 中执行此操作,但是,我认为这不会影响如何解决这个问题。

访问以前编译的方法的 C# 脚本

您需要

更改一些内容。

MainClassCalled需要可供其他程序集访问,因此请使它们public。此外,还需要添加对当前程序集的引用,以便能够在脚本代码中访问它。因此,从本质上讲,您的代码最终将如下所示:

public class MainClass

public static void Called()

var csc = new CSharpCodeProvider();
var ca = Assembly.GetExecutingAssembly();
var cp = new CompilerParameters();
cp.GenerateInMemory = true;
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("mscorlib.dll");
cp.ReferencedAssemblies.Add(ca.Location);
var res = csc.CompileAssemblyFromSource(
    cp,
    @"using System; 
        public class TestClass
        { 
            public int testvar = 5;
            public string Execute() 
            { 
                scriptingTest.MainClass.Called();
                return ""Executed."";
            }
        }"
);

运行测试的输出如下所示:

从脚本调用。
执行。
5