簡體   English   中英

+帶有空操作數的字符串連接運算符

[英]+ string concat operator with a null operand

一位同事向我展示了一種非常奇怪的行為,我想知道是否有人可以解釋我原因。

一個有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;
}

當在str2null的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個對象的連接,其中一個對象是非空的, 提供了返回null的ToString的覆蓋。 顯然,這種情況並非如此。

這種情況很可能是由以下原因之一引起的:

  • _vars Method_vars為null
  • 由於誤用_vars在多線程應用程序,的內部狀態_vars已被損壞,從而導致NullReferenceException當操作者[]被使用。

問題在於Method對象的實現。 由於+ Operator實現將空值解釋為空字符串 str2設置時,actuall null值永遠不會進入構造函數。 在相反的情況下, str1直接作為空值輸入,並且可能取決於實現導致空引用異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM