微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何评估方法返回返回的内容的原因

您使用什么策略向用户提供某种方法“失败”的原因

例:

public List<Balance> GetBalanceFinale(Periode periode)
    {
        if (periode == null || periode.DateStart >= DateTime.Now || isBalanceFinished(periode.PeriodeID))
            return null;

        //My other code...
     }

我想告诉用户哪些步骤出错了.我不想在这样的课程中使用消息框.我无法返回失败的描述,因为我已经返回了一些内容.

你通常做什么?有什么建议?谢谢!

解决方法

我假设你不想抛出异常,否则你已经做过了.类似于警报/警告而不停止执行程序.在这种情况下,您仍然可以使用异常,只是不要抛出异常,而是将其作为out参数传递,或者将其放在用户可以根据需要访问它的位置.如果这似乎超过顶部,那么只需使用消息.

将其定义为“尝试”方法可能是个好主意.很明显,该方法在某些条件下容易出现故障.

这些都是不同的选择:

public bool TryGetBalanceFinale(Periode periode,out List<Balance> list,out string msg)
{
    // return false if anything is wrong,and have an out parameter for the result & msg
}

public bool TryGetBalanceFinale(Periode periode,out Exception ex)
{
    // return false if anything is wrong,and have an out parameter for the exception
}

前两个是我的两个首选方法.以下是可能性,但它们有点不标准:

public Tuple<string,bool> TryGetBalanceFinale(Periode periode,out List<Balance> list)
{
    // return false if anything is wrong,and include message in the returned Tuple
}


// an anonymous type approach
public object TryGetBalanceFinale(Periode periode,out List<Balance> list)
{
    return new {
       Successful = false,Message = // reason why here
    };
}

// a functional approach
public List<Balance> list GetBalanceFinale(Periode periode,Action<String> messageAct)
{
   // when something is wrong,do:
   messageAct("Something went wrong..."); 
}

我认为当你考虑如何使用它时,’尝试’策略最有意义:

string message;
List<Balance> result;

if (!TryGetBalanceFinale(periode,out result,out message))
{
    // examine the msg because you kNow the method Failed
    Console.WriteLine(message); 
}
else
{
    // you kNow the method succeeded,so use the result
    Console.WriteLine("The result is: " + result.ToString()); 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐