using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
class Test
{
static void Main()
{
string str = @"\u5f00\u53d1\r\n\""换行\""\x8bed\u8a00";
string str1 = Convert(str);
Console.WriteLine("[{0}] -> [{1}]", str, str1);
}
static string Convert(string s)
{
return (new MyString(s)).Parse();
}
}
sealed class MyString
{
object instance;
MethodInfo method;
public MyString(string expression)
{
string className = "MyString";
string methodName = "Parse";
string code = string.Format("using System;sealed class {0}{{public string {1}(){{return \"{2}\";}}}}",
className, methodName, expression);
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, code);
if(cr.Errors.Count > 0)
{
string msg = "MyString(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance(className);
method = instance.GetType().GetMethod(methodName);
}
public string Parse()
{
return (string)method.Invoke(instance, null);
}
}
/* 程序输出:
[\u5f00\u53d1\r\n\"换行\"\x8bed\u8a00] -> [开发
"换行"语言]
*/