连接两个字符串,如果都为 null,则为 null

Concatenate two strings and get null if both are null

我正在寻找一种解决方案来连接两个字符串值并得到 null 作为结果,如果两者都是 nullstring1 + string2string.Concat(string1, string2)string.Join(string1, string2) 的 None 有效。研究表明,这是因为这些方法在内部将 null 视为空字符串。

如何解决?

是这样的吗?

public class StringTest
{
    public string CustomConcat(string one, string two) => 
        one == null && two == null 
            ? null 
            : string.Concat(one, two);

    [Test]
    public void ConcatTest()
    {
        Assert.IsNull(CustomConcat(null, null));
        Assert.AreEqual("one", CustomConcat("one", null));
        Assert.AreEqual("two", CustomConcat(null, "two"));
        Assert.AreEqual("onetwo", CustomConcat("one", "two"));

        // finally, a test for (a + b) ?? (c + d)
        Assert.AreEqual("threefour", CustomConcat(null, null) ?? CustomConcat("three", "four"));
    }
}

因为你的实际公式是

(a + b) ?? (c + d) // assumes that null + null == null in (a + b)

我建议改写成

a == null && b == null ? c + d : a + b

提供了预期的结果:

  • 如果 ab 都是 null 我们有 c + d
  • a + b否则

如果你想在所有 a, b, c, d 都是 null 时得到 null(非空字符串):

a == null && b == null ? 
  c == null && d == null 
    ? null 
    : c + d 
    : a + b;

是的,不同的方法调用处理不同的前提条件,但您始终可以创建自己的函数来处理“自定义”前提条件。

作为最简单的选项,您可以尝试这样的操作:

String concatenateStrings(string s1, string s1) {
return (s1 == null && s2 == null)? null : String.concat(s1,s2);
}

你可以这样做:

            var textResult = string.Empty;

            if (string.IsNullOrWhiteSpace(text1) && 
string.IsNullOrWhiteSpace(text2))
            {
                textResult = null;
            }
            else
                if (!string.IsNullOrWhiteSpace(text1) && 
string.IsNullOrWhiteSpace(text2))
                {
                    textResult = text1;
                }
                else
                    if (string.IsNullOrWhiteSpace(text1) && 
!string.IsNullOrWhiteSpace(text2))
                    {
                        textResult = text2;
                    }

            textResult = $"{text1} {text2}";

或者更好的方式:

        textResult = (!string.IsNullOrWhiteSpace(text1) && 
string.IsNullOrWhiteSpace(text2)) ?
            text1 :
                (string.IsNullOrWhiteSpace(text1) && 
!string.IsNullOrWhiteSpace(text2)) ?
                        text2 :
                        (string.IsNullOrWhiteSpace(text1) && 
!string.IsNullOrWhiteSpace(text2)) ?
                        text2 :
                        $"{text1} {text2}";