为什么我不能在调试器中使用新字符串?

Bri*_*ian 16 c# debugging visual-studio

以下代码成功编译:

string foo = new string(new char[] { 'b', 'a', 'r' });
Run Code Online (Sandbox Code Playgroud)

如果粘贴到监视窗口或立即窗口中,则无法评估以下代码:

new string(new char[] { 'b', 'a', 'r' });
Run Code Online (Sandbox Code Playgroud)

错误消息是:

'new string(new char[] { 'b', 'a', 'r' })' threw an exception of type 'System.ArgumentException'
    base {System.SystemException}: {"Only NewString function evaluation can create a new string."}
    Message: "Only NewString function evaluation can create a new string."
    ParamName: null
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Jar*_*Par 23

C#表达式计算器使用ICorDebugEval&ICorDebugEval2interfaces在调试会话期间与CLR交互.该接口不允许在string类型上调用任何构造函数.相反,它强制所有调用创建一个新的实例string来完成该ICorDebugEval::NewString方法.C#EE string在EE中不是特殊情况,因此它尝试直接调用构造函数并失败.

请注意,在Visual Studio 2010中,您不会在VB.Net中看到此异常.它将string通过评估参数并将结果string对象转发到构造函数来进行特殊情况调用.ICorDebugEval::NewString

  • 需要注意的是,作为一种解决方法,你可以使用它:new System.Text.StringBuilder().Append(new char [] {'b','a','r'})).ToString() (3认同)