加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:00:05 所属栏目:百科 来源:网络整理
导读:您使用什么策略向用户提供某种方法“失败”的原因 例: public ListBalance GetBalanceFinale(Periode periode) { if (periode == null || periode.DateStart = DateTime.Now || isBalanceFinished(periode.PeriodeID)) return null; //My other code... }
您使用什么策略向用户提供某种方法“失败”的原因

例:

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()); 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读