这是一个非常笼统且可能是常见的问题,但我无法在网上找到答案。
我正在寻找一种合理的方法来为可能在某些部分失败但在其他部分仍然成功的应用程序创建状态代码。
假设我有一个应用程序运行某种算法。 在我们得到结果后,应用程序应该做 3 件事:
- 通过电子邮件发送结果
- 将结果保存到Db
- 将结果发送到另一个集成的国外应用程序。
我需要创建一个状态代码,其中包含每个独立步骤的状态,并且可以指示单个或多个失败。
有什么常见的做法吗?
最佳答案
你应该使用标志枚举:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
https://msdn.microsoft.com/library/ms229062(v=vs.100).aspx
在这里你可以找到一些很好的例子 .HasFlag
https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx
在你的情况下它可能是这样的(当然它可以扩展,它真的取决于你的设计和要求):
[Flags]
public enum ReturnStatus
{
NoErrors = 0,
DBError = 1,
ThirdPartyError = 2,
EmailError = 4,
EmailSend = 8
//This could also be an option, so i just added it here as example, but i'm a bit confused if this is used as a return status or the current state of a task
//Example: when database failed, and the algorithm doesn't event attempts to send a mail, and when you want to rerun a task it could be usefull
}
ReturnStatus ret = ReturnStatus.DBError | ReturnStatus.EmailError;
if( ret.HasFlag(ReturnStatus.EmailError) ) {
//Email failed to send
}
if( ret.HasFlag(ReturnStatus.DBError) ) {
//Db save failed
}
关于c# - 定义返回状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33759259/