【问题标题】:How to compile and run C# code at runtime where the compiled code can access the rest of the program如何在运行时编译和运行 C# 代码,编译后的代码可以访问程序的其余部分
【发布时间】:2013-06-16 13:13:38
【问题描述】:

我有一个 C# 游戏,我希望让我们的脚本编写者编写如下所示的小代码文件,以便我们可以修补和修改我们的一些系统。

namespace Game.Creatures
{
    public class Zombie : Creature
    {
        public override float MovementRange { get { return 12; } }
        public override float AttackDamage { get { return 5; } }
        public override float TurnSpeed { get { return 2; } }
        public override float WalkSpeed { get { return 1.7f; } }
        public override float RunSpeed { get { return 2.5f; } }
        public override float TimeBetweenAttacksSeconds { get { return 0; } }
        public override bool CanAttack { get { return false; } }

        public Zombie(Vector3 in_Position, Vector3 in_Scale)
        {
            Health = MaxHealth = 40;
            CurrentAi = new Ai_Simple(this) {RecalcPathIn = -1};
        }

        public override void Update(GameTime in_GameTime) { base.Update(in_GameTime); }
        public override void Render(GameTime in_GameTime) { base.Render(in_GameTime); }
    }
}

如您所见,该文件使用了游戏中的类型和方法,这是否可能,或者任何运行时创建的代码都需要限制在其自身中?

如果它也可以在 360 上运行,则奖励。

编辑:Paint.net 有一个代码实验室插件可以做到这一点,所以我知道它一定是可能的。

【问题讨论】:

  • 这需要很多思考。
  • 它没有,只需添加对您自己的程序集的引用。包括你的EXE。您允许编写脚本的类需要是公共的。当然,您需要让脚本编写者获得对正确对象的引用。

标签: c# compilation runtime


【解决方案1】:

Is it possible to dynamically compile and execute C# code fragments? 处理同样的事情。能够引用您的类只是意味着您要引用的程序集之一应该是其中包含Creature 的程序集。例如

var parameters = new CompilerParameters(
 new[] { "mscorlib.dll", "System.Core.dll", "MyAssembly.dll" }, "foo.exe", true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多