[英]What is the terminology for what this method attempts?
我不知道:
但我認為意圖非常明顯。
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
我在做什么? 這是瘋了還是有幫助的? 這似乎有幫助。
我認為使用OrNew
方法的想法很好。 特別是如果你正在努力建立一個流暢的界面。 但是,我會改變3件事
ThrowIfNull
)。 這使得某人無法閱讀OrNew
電話了解它的作用。 new
約束支持較不安全的Activator.CreateInstance<T>()
調用 DebugLogic
以外的DebugLogic
。 通常(但不總是)擴展方法容器以Extensions
名結尾。 例如
public static class LogicExtensions {
public static T OrNew<T>(this T obj) where T : class, new() {
if (obj != null) {
return obj;
}
return new T();
}
}
此操作的名稱顯然是: DefaultIfNull
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.