gpt4 book ai didi

c# - 我可以在运行时扩展包含 C# 文字表达式的字符串吗

转载 作者:太空狗 更新时间:2023-10-29 18:11:25 26 4
gpt4 key购买 nike

如果我有一个包含 c# 字符串文字表达式的字符串,我可以在运行时“扩展”它吗

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

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

Can I convert a C# string value to an escaped string literal , 但反过来呢?

最佳答案

类似于 Mikael 的回答,但使用的是 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;
}

您最好使用通配符字典并在字符串中替换它们。

关于c# - 我可以在运行时扩展包含 C# 文字表达式的字符串吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3298075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com