c# - + 带空操作数的字符串连接运算符

标签 c# .net

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

具有 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 个对象的连接,其中一个对象是非空的并且提供了 ToString 返回 null。显然,这里的情况并非如此。

这种情况很可能是由以下原因之一引起的:

  • _varsMethod 被调用时为 null
  • 由于在多线程应用程序中误用了 _vars_vars 的内部状态已被破坏,导致 NullReferenceException当使用运算符 [] 时。

关于c# - + 带空操作数的字符串连接运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860356/

相关文章:

c# - Roslyn 将内容嵌入程序集

c# - DbContext 查询性能较 ObjectContext 差

C# HttpListener 'Bad request' 问题

c# - LINQ Select Many 语句

c# 在日期范围之间退款

.net - Winforms 无法在 VS2012 中加载文件或程序集 'Microsoft.ReportDesigner, Version=10.0.0.0'

c# - 用于独立桌面应用程序 C# .net 的嵌入式数据库

c# - 如何重构重复的事件处理代码

.net - 如何手动计算 .Net 类的传出耦合 (Ce)?

c# - WCF 服务 - 向后兼容性问题