如果我有一个包含 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";
}
Like 我可以将 C# 字符串值转换为转义字符串文字吗 https://stackoverflow.com/questions/323640/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;
}
您最好使用通配符字典并在字符串中替换它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)