2016-08-30 74 views
-2

我有这样C#有没有办法让这个语句更加紧凑?

return x != null ? new Something() { Foo = x.Something, Bar = x.SomethingElse } : null; 

一段代码,我不能在这里使用空传播经营者,因为它是我想的正好相反(这要我定义什么返回如果xnull,不若x不是null)。但我不喜欢我拥有的东西。

有没有更好的方法?

回答

3

您可以创建一个扩展方法关闭的任何x是,这将让你然后做:

return x?.toSomething(); 
+3

你甚至不需要使用''.''就可以让你的扩展方法足够健壮以支持'this'参数传入的空值。你可以做'x.toSomething();' –

1

比它更紧凑此使用常规语法没有

顺便说一句,你可以实现一个扩展方法:

return x.MapIfNotNull(o => new Something { Foo = o.Something, Bar = o.SomethingElse }); 

凡扩展方法将如下所示:

public static class ObjectExtensions 
{ 
    public static T MapIfNotNull<T, TReturn>(this T some, Func<T, TReturn> map) 
      where T : class 
    { 
      Contract.Requires(map != null); 

      return some != null ? map(some) : null; 
    } 
} 

你甚至可以超越并简化实例:

public static class ObjectExtensions 
{ 
    public static T MapIfNotNull<T, TReturn>(this T source, Func<T, TReturn, TReturn> map) 
      where TReturn : class, new() 
    { 
      Contract.Requires(map != null); 

      if(source == null) 
      return; 

      TReturn target = map(source, new TReturn()); 

      return target; 
    } 
} 

...并使用它如下:

return x.MapIfNotNull<A, B>((s, t) => { t.Foo = s.Something; t.Bar = s.SomethingElse; }); 

或者你甚至可以使用AutoMapper简化甚至更多:

return mapper.Map<A, B>(a); 
1

这不是更短,当你考虑的字符数,但它宽短,从而更容易适应于您的屏幕,并非常易读:

只需将其分成两个语句。只是够聪明的,以免试图变得太聪明。

if (x == null) return null; 
return new Something { Foo = x.Something, Bar = x.SomethingElse }; 
相关问题