从字符串(外部文本文件)执行当前应用程序中的C#代码

时间:2018-04-08 20:45:23

标签: c#

我必须开发一个可以从用户创建的文本文件中执行某些功能的应用程序。

我搜索并找到了一些帖子:

Execute code lines from a text file in C#

Execute C# code in a String?

How to compile a C# file with Roslyn programmatically?

但我没找到我要找的东西......

我不想将输入字符串代码作为外部或分隔的名称空间执行...

我正在寻找的是从字符串值

执行主要代码的某些部分

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;


namespace ConsoleApp1
{

    public partial class Window : MainWindow
    {
        string internal_message = "Hello World!"; /// a value set in main code
        public UserControl1()
        {
            InitializeComponent();
        }


     //////////////////////////////////// I want this part be executed from a string [
    void Saysomething()
    {

            MessageBox.Show(internal_message); /// get internal message from main values
        }

//////////////////////////////////// ]

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Saysomething(); //// run function executed from text data
        }
    }
}

我的功能很复杂,我需要一个通用的解决方案 在3ds max maxscript中我们称之为"执行"

它接受字符串并在相同的代码和命名空间中将其作为动态代码执行:

myvalue = "val = 30";
execute(myvalue);
print val;

/// result 
30

我需要在c#中使用相同的内容。请尽量不要使用 roslyn

1 个答案:

答案 0 :(得分:1)

看看CS-Script library我认为这是你最接近你想要的东西,你可以选择在后台使用它。