我的同事向我展示了一个非常奇怪的行为,我想知道是否有人能够解释一下。
一个具有两个字符串参数的基本构造函数:
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 页面中调用此构造函数时,一切都可以正常工作,因为如果字符串拼接操作符 +
的操作数为 null
,则将替换为空字符串。但是,当在后台线程中以
str2
为 null
调用此构造函数时,会触发一个 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()
this.s2
有什么用?堆栈跟踪是什么?您能发布可重现的代码供我们测试吗?您在哪里进行空值检查?是在实例化MyClass
之前、在执行Method
之前,还是在构造函数开始时? - Chris SinclairMethod
函数是做什么用的? - Damien_The_Unbelieverforeach
循环替换为适当的String.Join
调用 :-) - sloth