Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

Can I expand a string that contains C# literal expressions at runtime

If I have a string that contains a c# string literal expression can I "expand" it at runtime

    public void TestEvaluateString()
    {
        string Dummy = EvalString( @"Contains 
 new line");
        Debug.Assert(Dummy == "Contains 
 new line");
    }

    private string EvalString(string input)
    {
        return "Contains 
 new line";
    }

Like Can I convert a C# string value to an escaped string literal, but in reverse?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Similar to Mikael answer but using the CSharpCodeProvider:

    public static string ParseString(string txt)
    {
        var provider = new Microsoft.CSharp.CSharpCodeProvider();
        var prms = new System.CodeDom.Compiler.CompilerParameters();
        prms.GenerateExecutable = false;
        prms.GenerateInMemory = true;
        var results = provider.CompileAssemblyFromSource(prms, @"
namespace tmp
{
    public class tmpClass
    {
        public static string GetValue()
        {
             return " + """ + txt + """ + @";
        }
    }
}");
        System.Reflection.Assembly ass = results.CompiledAssembly;
        var method = ass.GetType("tmp.tmpClass").GetMethod("GetValue");
        return method.Invoke(null, null) as string;
    }

You might be better off using a dictionary of wildcards and just replacing them in the string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...