C#Replace导致找不到对象引用错误

Sin*_*ard -1 c# replace object-reference

在字符串clientNameStr上使用"替换"会导致"找不到对象引用"错误.

// Get client name
clientName = currentUser.GetValue("ClientName");
string clientNameStr = (string)clientName;
string clientURLStr = string.Empty;
clientURLStr = clientNameStr.Replace(' ', '-');
// clientURLStr = "ST9215-Stanic-Parts-Ltd";
Run Code Online (Sandbox Code Playgroud)

如果我在注释掉的字符串中替换(并注释掉现有的字符串)它工作正常,所以它必须与替换函数有关,但是什么?尝试使用"和'引号,同样的结果.

任何帮助将不胜感激.

谢谢,奥利.

Jon*_*eet 5

这基本上表明currentUser.GetValue("ClientName")返回空引用1.我们不知道是什么currentUser.GetValue("ClientName"),但有两种选择:

  • 正确地返回null,你应该处理它
  • 不应该返回null,你需要修复它(如果它遇到这种情况可能抛出异常)

1可能会返回一个非空引用,并在下一行中使用用户定义的转换字符串返回null - 但不太可能.我们无法确定,因为我们不知道它的类型clientName.