如何在c#中将字符串转换为可运行的代码段

时间:2016-01-17 17:09:25

标签: c# converter

在我正在创建的程序中,我需要能够将字符串变量转换为C#中可运行的代码段。

例如我们有

myEditText.addTextChangedListener(new CustomFormatWatcher());

非常感谢任何反馈。

2 个答案:

答案 0 :(得分:1)

您可以使用lprun.exe附带的LINQPaddocumentation很好地解释了用法。

总之,你传递了你的C#(也是其他可用的语言)代码,这些代码可以说是存储在Foo.txt中的可执行文件中,然后执行。

lprun.exe -lang=p Foo.txt

p代表Program,请参阅文档了解详情。

答案 1 :(得分:1)

您需要在运行时实际编译该方法,以便像这样使用它们(即按字符串传递方法然后编译它)。

例如,你可以:

在运行时创建方法

ComboBox peopleComboBox = new ComboBox();
List <Person> people; //it's initialized elsewhere
private void btnLoadPeopleName_Click(object sender, RoutedEventArgs e)
    {

        peopleComboBox.IsEnabled = true;
        peopleComboBox.Height = 1280; //I wanted to set it Auto with double.NaN but it won't open. Always set to 0 during debugging.

        peopleComboBox.ItemsSource = people;
        peopleComboBox.DisplayMemberPath = "first_name";
        peopleComboBox.SelectedIndex = 0;

        peopleComboBox .SelectionChanged +=peopleComboBox_SelectionChanged;

        peopleComboBox.Visibility = Visibility.Visible;
        peopleComboBox.IsDropDownOpen = true; //this should open it, right?
    }

使用

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

public static class RuntimeHelpers
{
    public static MethodInfo CreateFunction()
    {
        //You can pass it through parameter
        string code = @"
            using System;

            namespace RuntimeFunctions
            {                
                public class Functions
                {                
                    public static void PrintStuff(string input)
                    {
                        Console.WriteLine(input);
                    }
                }
            }";

        //Compile on runtime:
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), code);

        //Compiled code threw error? Print it.
        if (results.Errors.HasErrors)
        {
            foreach (var error in results.Errors)
            {
                Console.WriteLine(error);
            }
        }

        //Return MethodInfo for future use
        Type function = results.CompiledAssembly.GetType("RuntimeFunctions.Functions");
        return function.GetMethod("PrintStuff");
    }
}

基于LumírKojecký撰写的文章: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime