简体   繁体   English

C#-更有效的三元运算符

[英]C# - A more efficient ternary operator

I was making a program in which I want to check if a string is equal to "" , and if it isn't use it, but if it is, use the default value. 我在编写一个程序,其中要检查字符串是否等于"" ,以及是否不使用它,但是如果使用,请使用默认值。 I know I can do string != "" ? string : "default value" 我知道我可以做string != "" ? string : "default value" string != "" ? string : "default value" , however, I feel like this is inefficient, as I keep typing out string . string != "" ? string : "default value" ,但是,由于我不断键入string ,因此我觉得这效率很低。 Of course, writing out string is no problem for me, but, if in another project, I have to reference a string with a long package name, it would be a little more annoying. 当然,写出一个string对我来说没有问题,但是,如果在另一个项目中,我必须引用一个带有长包名的字符串,那会有些烦人。

At the moment there is no operator that can do what you want. 目前,没有操作员可以执行您想要的操作。

But there is actually a proposal for a "Default-or-Empty Coalesce operator", here: 但实际上,这里有一个“默认或空的合并运算符”的建议:

https://github.com/dotnet/csharplang/issues/183 https://github.com/dotnet/csharplang/issues/183

The best you can do at the moment is to declare an extension method like this: 目前您能做的最好的就是声明一个扩展方法,如下所示:

    public static string NullIfEmpty(this string str)
    {
        return string.IsNullOrEmpty(str) ? null : str;
    }

and use it like this: 并像这样使用它:

var foo = yourString.NullIfEmpty() ?? "default value";

According to DavidG's option and helpful link, you could use this extension function. 根据DavidG的选项和有用的链接,您可以使用此扩展功能。

public static string IfEmpty(this string str, string alternate)
{
    return str?.Length == 0 ? str : alternate;
}

(This will return the alternate string even if the 'str' is null) (即使'str'为null,这也会返回备用字符串)

And use as mystring.IfEmpty("something else") 并用作mystring.IfEmpty("something else")

Source: What is the difference between String.Empty and "" (empty string)? 来源: String.Empty和“”(空字符串)有什么区别? .

Also you don't need to reference a really long string. 另外,您不需要引用很长的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM