一位同事向我展示了一个非常奇怪的行为,我想知道是否有人可以向我解释原因。
具有 2 个字符串参数的基本构造函数:
public MyClass(string str1, string str2)
{
this.s1 = str1;
this.s2 = str2;
this.s3 = Method(str2 + "._className", str1);
}
方法是:
public string Method(string key, string defaultValue)
{
List<string> list = _vars[key];
if (list == null) return defaultValue;
string res = "";
foreach (string s in list)
{
if (res != "") res += ",";
res += s;
}
return res;
}
当在 str2
为 null
的 aspx 页面中调用此 ctor 时,一切正常,因为如果字符串连接操作数 +
是null
,替换为空字符串。
但是当在后台线程中使用 str2
作为 null
调用此 ctor 时,将触发 NullReferenceException
。
在使用之前通过测试 str2 != null
解决了这个问题,但我真的很想知道为什么相同的代码有时会触发异常,有时不会!
这是堆栈跟踪:
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace:
at MyClass..ctor(String str1, String str2)
at AbandonedCartsNotificationJob.NotifyAbandonedCarts() in AbandonedCartsNotificationJobPartial.cs:line 39
at AbandonedCartsNotificationJob.work() in AbandonedCartsNotificationJob.cs:line 15
at MyRuntime.JobManager.run()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
最佳答案
.NET Framework 的字符串连接实现中存在一个不明显的错误,但它只影响 4 个对象的连接,其中一个对象是非空的并且提供了 ToString
返回 null。显然,这里的情况并非如此。
这种情况很可能是由以下原因之一引起的:
_vars
在Method
被调用时为 null- 由于在多线程应用程序中误用了
_vars
,_vars
的内部状态已被破坏,导致NullReferenceException
当使用运算符[]
时。
关于c# - + 带空操作数的字符串连接运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860356/