chi*_*oro 55 .net c# conditional-operator conditional-expressions
只是为了好奇/方便:C#提供了两个我知道的很酷的条件表达式功能:
string trimmed = (input == null) ? null : input.Trim();
Run Code Online (Sandbox Code Playgroud)
和
string trimmed = (input ?? "").Trim();
Run Code Online (Sandbox Code Playgroud)
对于我经常遇到的情况,我想念另一个这样的表达:
如果输入引用为null,则输出应为null.否则,输出应该是访问输入对象的方法或属性的结果.
我在第一个例子中完成了这一点,但是(input == null) ? null : input.Trim()非常冗长且难以理解.
这种情况是否有另一个条件表达式,或者我可以??优雅地使用运算符吗?
Jon*_*eet 49
像Groovy的null安全解除引用运算符?
string zipCode = customer?.Address?.ZipCode;
Run Code Online (Sandbox Code Playgroud)
我认为C#团队已经对此进行了研究,发现它并不像人们想象的那样优雅地设计......虽然我没有听说过问题的细节.
我不相信目前语言中有任何这样的东西,我害怕......我还没有听说过任何计划,尽管这并不是说它不会在某个时刻发生.
编辑:它现在将成为C#6的一部分,作为"零条件运算符".
小智 10
您可以选择自定义Nullify类或NullSafe扩展方法,如下所述:http://qualityofdata.com/2011/01/27/nullsafe-dereference-operator-in-c/
用法如下:
//Groovy:
bossName = Employee?.Supervisor?.Manager?.Boss?.Name
//C# Option 1:
bossName = Nullify.Get(Employee, e => e.Supervisor, s => s.Manager,
m => m.Boss, b => b.Name);
//C# Option 2:
bossName = Employee.NullSafe( e => e.Supervisor ).NullSafe( s => s.Boss )
.NullSafe( b => b.Name );
Run Code Online (Sandbox Code Playgroud)
目前我们只能写一个扩展方法,如果你不想重复自己,我担心.
public static string NullableTrim(this string s)
{
return s == null ? null : s.Trim();
}
Run Code Online (Sandbox Code Playgroud)
作为一种解决方法,您可以使用基于Maybe monad的方法.
public static Tout IfNotNull<Tin, Tout>(this Tin instance, Func<Tin, Tout> Output)
{
if (instance == null)
return default(Tout);
else
return Output(instance);
}
Run Code Online (Sandbox Code Playgroud)
用这种方式:
int result = objectInstance.IfNotNull(r => 5);
var result = objectInstance.IfNotNull(r => r.DoSomething());
Run Code Online (Sandbox Code Playgroud)
没有任何内置功能,但如果你愿意的话,你可以将它全部包含在扩展方法中(虽然我可能不会打扰).
对于这个具体的例子:
string trimmed = input.NullSafeTrim();
// ...
public static class StringExtensions
{
public static string NullSafeTrim(this string source)
{
if (source == null)
return source; // or return an empty string if you prefer
return source.Trim();
}
}
Run Code Online (Sandbox Code Playgroud)
或者更通用的版本:
string trimmed = input.IfNotNull(s => s.Trim());
// ...
public static class YourExtensions
{
public static TResult IfNotNull<TSource, TResult>(
this TSource source, Func<TSource, TResult> func)
{
if (func == null)
throw new ArgumentNullException("func");
if (source == null)
return source;
return func(source);
}
}
Run Code Online (Sandbox Code Playgroud)