小编Syl*_*v21的帖子

+带有空操作数的字符串连接运算符

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

一个有2个字符串参数的基本构造函数:

    public MyClass(string str1, string str2)
    {
        this.s1 = str1;
        this.s2 = str2;
        this.s3 = Method(str2 + "._className", str1);
    }
Run Code Online (Sandbox Code Playgroud)

方法是:

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;
}
Run Code Online (Sandbox Code Playgroud)

当使用str2as 在aspx页面内调用此ctor时null,一切正常,因为如果字符串连接的操作数+null,则替换空字符串.

但是,当这个构造函数被调用,str2null在后台线程,一个NullReferenceException被解雇. …

.net c#

8
推荐指数
1
解决办法
437
查看次数

标签 统计

.net ×1

c# ×1