好的,因爲我注意到你實際上想要ContentFrom模式有點晚了,我盡了最大努力想出了你的示例在我的原始版本下的翻譯版本回答
在一般情況下,我使用下面的範例這樣的情況。搜索和替換這裏的具體方法和那裏:)
IEnumerable<T> ValueSources()
{
yield return _value?? _alternative;
yield return SimpleCalculationFromCache();
yield return ComplexCalculation();
yield return PromptUIInputFallback("Please help by entering a value for X:");
}
T EffectiveValue { get { return ValueSources().FirstOrDefault(v => v!=null); } }
注意你怎麼能現在做v!=null
任意適合您的需要「有趣」。
注意評價怎麼也懶可以確保_alternative設置爲「有趣」的計算是從來沒有做過當_value或值
這是我在把你的樣品放入該模具的初步嘗試。注意:我如何加入了很多管道,以確保這實際上編譯成獨立的C#EXE:
using System.Collections.Generic;
using System.Linq;
using System;
using T=System.String;
namespace X { public class Y
{
public static void Main(string[]args)
{
var content = Sources().FirstOrDefault(c => c); // trick: uses operator bool()
}
internal protected struct Content
{
public T Value;
public ContentFrom Mode;
//
public static implicit operator bool(Content specimen) { return specimen.Mode!=ContentFrom.None && null!=specimen.Value; }
}
private static IEnumerable<Content> Sources()
{
// mock
var Request = new { QueryString = new [] {"id"}.ToDictionary(a => a) };
if (!String.IsNullOrEmpty(Request.QueryString["id"]))
yield return new Content { Value = GetContent(Convert.ToInt64(Request.QueryString["id"])), Mode = ContentFrom.Query };
if (DefaultId != null)
yield return new Content { Value = GetContent((long) DefaultId), Mode = ContentFrom.Default };
yield return new Content();
}
public enum ContentFrom { None, Query, Default };
internal static T GetContent(long id) { return "dummy"; }
internal static readonly long? DefaultId = 42;
} }
爲什麼ContentMode類「內容」的不是財產?如果您將其作爲「內容」類的一部分,則代碼可能更短,更易讀。而且您不需要ContentFrom.None枚舉,因爲NULL內容對象將替換該枚舉的邏輯。 – SolutionYogi 2011-03-23 03:56:02
因爲「內容」來自第三方API。我必須爲這個項目使用一個......我想我可以嘗試把它包裝起來,就像這裏的其他建議一樣。 – Andy 2011-03-24 15:53:22