Khh*_*Khh 3 c# extension-methods .net-3.5
我被问到什么是错的/如何修复以下场景
Customer customer = null;
customer.WhenNull(c => new Customer())
.Foo();
// instead of
Customer customer = null;
if (customer == null)
{
customer = new Customer();
}
customer.Foo();
Run Code Online (Sandbox Code Playgroud)
一位开发人员向我发送了他的WhenNull扩展版本
public static T WhenNull<T>(this T source, Action<T> nullAction)
{
if (source != null)
{
return source;
}
if (nullAction == null)
{
throw new ArgumentNullException("nullAction");
}
nullAction(source);
return source;
}
Run Code Online (Sandbox Code Playgroud)
他的问题/意图是,他不想在lambda表达式中指定底层对象(在本例中为"customer")
Customer customer = null;
customer.WhenNull(c => customer = new Customer())
.Foo();
Run Code Online (Sandbox Code Playgroud)
我以为这不可能做到.
它是否正确?
你可以这样做:
static T WhenNull<T>(this T t) where T : class, new()
{
return t ?? new T();
}
Run Code Online (Sandbox Code Playgroud)
还指出:你希望使用Func<T>不Action<T>按你的示例代码.
编辑2:
你可能想要这个:
static T WhenNull<T>(this T t, Func<T> init) where T : class
{
if (t == null)
{
t = init(); // could return here, but for debugging this is easier
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
用法:
something.WhenNull(() => new Something()).Foo()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |