gpt4 book ai didi

c# - 检查引用参数值或返回 bool 值?

转载 作者:太空狗 更新时间:2023-10-30 00:17:06 26 4
gpt4 key购买 nike

我正在使用具有以下签名的方法:

public static bool TryAuthenticate(string userName, string password, 
string domainName, out AuthenticationFailure authenticationFailure)

该方法声明:bool authenticated = false; 然后继续验证用户。

每当 authenticated 设置为 true 或 false 时,authenticationFailure 将设置为 AuthenticationFailure.FailureAuthenticationFailure.Success 相应地。

所以基本上我可以使用 authenticationFailure 或方法的返回值来检查结果。然而,在同一方法中使用这两种方法似乎毫无意义地违反了 DRY。

澄清一下,方法中的任何其他地方都没有使用 authenticationFailure,因此它看起来完全是多余的。

目前我正在这样做:

public static bool IsValidLDAPUser(string username, string password, string domain)
{
var authenticationStatus = new AuthenticationFailure();
if (ActiveDirectoryAuthenticationService.TryAuthenticate(username, password, domain, out authenticationStatus))
return true;
else return false;
}

但我可以这样做并得到一个类似的结果:

public static AuthenticationFailure IsValidLDAPUser(string username, string password, string domain)
{
var authenticationStatus = new AuthenticationFailure();
ActiveDirectoryAuthenticationService.TryAuthenticate(username, password, domain, out authenticationStatus)
return authenticationStatus;
}
  • 为什么要有一个与返回值做同样事情的引用参数?
  • 我应该使用哪个来检查结果,它有什么不同吗?
  • 这只是错误代码的情况还是我没有捕获要点?

提前致谢!

最佳答案

通常有比成功或失败更多的错误代码。也许此方法的设计者会为所有不同的故障类型添加更多枚举。

有时,也有不止一种成功类型——例如HTTP 在 200 和 300 block 中有很多返回码,在某种程度上都被认为是成功的。因此,bool 通常会告诉您它是否成功,而 enum 会提供更准确的信息。

有很多方法可以做到这一点,这个是不寻常的,但如果他们计划添加更多代码,则不反对 DRY。

另一种方法是仅封装到具有枚举和 IsSuccess 属性的 Result 类中。您甚至可以提供到 bool 的转换,以使其易于在 if 语句中使用。

关于c# - 检查引用参数值或返回 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3619691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com