此方法尝试的术语是什么?
我不知道:
- 这是否有效。
- 如果这是个好主意。
- 按顺序叫什么 了解更多相关信息。
但我认为其意图是相当明显的。
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
预期用途: var customer = order.Sale.OrNew().Customer.OrNew().Name
我在做什么?这是疯狂还是有帮助?它似乎很有帮助。
I don't know:
- if this works.
- if it's a good idea.
- what it is called in order
to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为使用
OrNew
方法的想法很好。特别是如果您正在努力制作流畅的界面。不过,我会改变 3 件事:ThrowIfNull
)。这使得某人无法阅读OrNew
调用并理解它的作用。new
约束来支持不太安全的Activator.CreateInstance()
调用,DebugLogic
以外的名称。通常(但并非总是)扩展方法容器以Extensions
结尾。例如
I think the idea of having an
OrNew
method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about itThrowIfNull
). This makes it impossible for someone to read anOrNew
call an understand what it does.new
constraint in favor of the less safeActivator.CreateInstance<T>()
callDebugLogic
. Generally (but not always) extension method containers end with theExtensions
.For example
这个操作的名称很明确:
DefaultIfNull
The name of this operation is clearly:
DefaultIfNull