返回第一种有效的方法,更优雅的方式?

And*_*ndy 3 c# design-patterns

最近我发现自己编写的方法连续调用其他方法,并根据哪种方法首先返回适当的值来设置一些值.我一直在做的是用一种方法设置值,然后检查值,如果它不好,那么我检查下一个.这是最近的一个例子:

private void InitContent()
{
    if (!String.IsNullOrEmpty(Request.QueryString["id"]))
    {
        Content = GetContent(Convert.ToInt64(Request.QueryString["id"]));
        ContentMode = ContentFrom.Query;
    }

    if (Content == null && DefaultId != null)
    {
        Content = GetContent(DefaultId);
        ContentMode = ContentFrom.Default;
    }

    if (Content == null) ContentMode = ContentFrom.None;
}
Run Code Online (Sandbox Code Playgroud)

如果不在数据库中,GetContent则应返回此方法.这是一个简短的例子,但你可以想象如果有更多的选择,这可能会变得笨重.有一个更好的方法吗?nullid

Eri*_*ert 9

空合并运算符可能具有您想要的语义.

q = W() ?? X() ?? Y() ?? Z();
Run Code Online (Sandbox Code Playgroud)

这基本上与:

if ((temp = W()) == null && (temp = X()) == null && (temp == Y()) == null)
    temp = Z();
q = temp;
Run Code Online (Sandbox Code Playgroud)

也就是说,q是W(),X(),Y()的第一个非null,或者如果它们都是null,那么Z().

你可以随意链接.

确切的语义不像我勾勒出来的那样; 类型转换规则很棘手.如果您需要确切的详细信息,请参阅规范.