否定空合并运算符

发布于 2024-09-01 17:18:03 字数 207 浏览 2 评论 0原文

我有一堆字符串需要使用 .Trim() ,但它们可以为空。如果我可以这样做,那就会更加简洁:

string endString = startString !?? startString.Trim();

如果左侧部分不为空,则基本上返回右侧部分,否则仅返回空值。我刚刚最终使用了三元运算符,但是是否可以使用空合并运算符来实现此目的?

I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like:

string endString = startString !?? startString.Trim();

Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

谁对谁错谁最难过 2024-09-08 17:18:03

您可以创建一个扩展方法,该方法在尝试修剪该值时返回 null

public String TrimIfNotNull(this string item)
{
   if(String.IsNullOrEmpty(item))
     return item;
   else
    return item.Trim();
}

请注意,您不能将其命名为 Trim,因为扩展方法无法覆盖实例方法。

You could create an extension method which returns null when it tries to trim the value.

public String TrimIfNotNull(this string item)
{
   if(String.IsNullOrEmpty(item))
     return item;
   else
    return item.Trim();
}

Note you can't name it Trim because extension methods can't override instance methods.

稚然 2024-09-08 17:18:03

不符合规范:不是我喜欢它,但你可以使用:

string endString = (startString ?? String.Empty).Trim();

符合规范,更好地作为像@Kevin's这样的扩展方法:

string endString = (startString == null ? null : startString.Trim());

Not to spec: Not that I like it, but you could use:

string endString = (startString ?? String.Empty).Trim();

To spec, better as an Extension method like @Kevin's:

string endString = (startString == null ? null : startString.Trim());
绝影如岚 2024-09-08 17:18:03
string endString = string.IsNullOrEmpty(startString) ? startString : startString.Trim();

尽管我还编写了一个名为“safeTrim”的字符串扩展方法,该方法可以在一种方法中执行您所描述的操作,而不必每次都使用此配方。查看 Kevin 的回复获取代码。

编辑:哇,我有各种各样的倒退、错误命名的变量和反向三元运算符,更有理由编写一个扩展方法并比我更好地进行代码检查!

string endString = string.IsNullOrEmpty(startString) ? startString : startString.Trim();

Though I've also gone the route of writing a string extension method called "safeTrim" which does what you're describing in one method instead of having to use this recipe every time. Check out Kevin's respone for the code.

EDIT: wow I had it all kinds of backwards, wrongly named variables and reversed ternary operators, all the more reason to write one extension method and code check it better than I did!

乱了心跳 2024-09-08 17:18:03

从 C# 6.0 (.NET Framework 4.6 / Visual Studio 2015) 开始,您可以使用 空条件成员访问

 string? endString = startString?.Trim();

Starting with C# 6.0 (.NET Framework 4.6 / Visual Studio 2015) you can use null-conditional member access:

 string? endString = startString?.Trim();
╄→承喏 2024-09-08 17:18:03

抱歉,我遇到了死灵术,但我也遇到了同样的问题,我使用 lambda 运算解决了这个问题。它不是最漂亮的,但它使我的代码保持简洁。

遗憾的是 C# 不支持静态导入或单个函数导入,但无论如何:

在某处定义此函数:

private static TResult N<TParent,TResult>(TParent parent, Func<TParent,TResult> operation) {
    if( parent == null ) return default(TResult);
    return operation( parent );
}

然后在示例中使用它:

String endString = N(startString, s => s.Trim());

N 函数返回 null如果第一个参数为 null,否则它将使用该值作为参数来计算指定的 lambda 函数。

当然,你可以像这样嵌套它。例如,要安全地取消引用长链,例如,

String someValue = someObject.SomeProperty.SomeOtherProperty.SomeMethod().SomeFinalProperty;

如果这些属性或方法中的任何一个返回 null,那么您必须在各处插入 null 检查,或者您可以这样做:

String someValue = N(N(N(N(someObject, o => o.SomeProperty), o => o.SomeOtherProperty), o => o.SomeMethod()), o => o.SomeFinalProperty);

正如我所说,它不是最漂亮的:)

您可以简化通过使 N 成为 System.Object 的扩展方法,如下所示:

String someValue = someObject.N( o => o.SomeProperty ).N( o => o.SomeOtherProperty ).N( o => o.SomeMethod() ).N( o => o.SomeFinalProperty );

...我认为这更整洁。

Sorry for the necromancy, but I was having this same problem and I solved this using a lambda operation. It isn't the prettiest, but it keeps my code succinct.

It's a shame C# doesn't support static imports or individual function imports, but anyway:

Define this function somewhere:

private static TResult N<TParent,TResult>(TParent parent, Func<TParent,TResult> operation) {
    if( parent == null ) return default(TResult);
    return operation( parent );
}

Then to use it in your example:

String endString = N(startString, s => s.Trim());

The N function returns null if the first argument is null, otherwise it will evaluate the specified lambda function with the value as the argument.

You can nest it, of course, like so. For example, to safely dereference a long chain, e.g.

String someValue = someObject.SomeProperty.SomeOtherProperty.SomeMethod().SomeFinalProperty;

if any of those properties or methods returns null then you have to insert null checks everywhere, or you could do this:

String someValue = N(N(N(N(someObject, o => o.SomeProperty), o => o.SomeOtherProperty), o => o.SomeMethod()), o => o.SomeFinalProperty);

As I said, it isn't the prettiest :)

You could simplify this by making N an extension method of System.Object, like so:

String someValue = someObject.N( o => o.SomeProperty ).N( o => o.SomeOtherProperty ).N( o => o.SomeMethod() ).N( o => o.SomeFinalProperty );

...which I think is a lot tidier.

自此以后,行同陌路 2024-09-08 17:18:03

使用

string endString = (startString ?? "").Trim();

如果 startString 为 null,则使用空字符串。但是,当 endString 为 null 时,不会返回 null。

快进到 2021 年:
10 年后,startString?.Trim() 绝对是更好的选择。这确实返回null

Use

string endString = (startString ?? "").Trim();

This uses an empy string if startString is null. This, however, does not return null when endString is null.

Fast-forward to 2021:
10 years later startString?.Trim() is definitely the better option. And this does return null.

汐鸠 2024-09-08 17:18:03

以下代码不会传播 null,但它接受 null 作为参数,并在这种情况下返回空字符串。

using Microsoft.VisualBasic;  // you need to add a reference to Microsoft.VisualBasic.dll

    ...
    string endString = Strings.Trim(startString);
    ...

鸭子跑...

The following doesn't propagate null but it accepts null as a parameter and returns an empty string in that case.

using Microsoft.VisualBasic;  // you need to add a reference to Microsoft.VisualBasic.dll

    ...
    string endString = Strings.Trim(startString);
    ...

duck&run...

策马西风 2024-09-08 17:18:03

作为旁注,如果您使用 .NET 4,有一个新的便捷方法 String.IsNullOrWhiteSpace

As as side note, if you're using .NET 4, there's a new convenient method String.IsNullOrWhiteSpace which you can use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文