gpt4 book ai didi

c# - 从 'using' 语句中的函数返回资源实例是否与直接在 'using' 语句中实例化资源相同?

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:58 24 4
gpt4 key购买 nike

我正在尝试遵循此处定义的“使用”最佳实践:

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

鉴于该规则,我认为这是错误的:

private PrincipalContext GetDomainContext(
out bool bFailedBecauseDomainServerIsInaccessible
)
{
bFailedBecauseDomainServerIsInaccessible = false;

try
{
return new PrincipalContext(
ContextType.Domain,
null
);
}
catch (PrincipalServerDownException downEx)
{
bFailedBecauseDomainServerIsInaccessible = true;
}
catch (Exception ex)
{
}

return null;
}

//calling logic...
PrincipalContext ctxDomain = null;
bool bErrorHittingDomainServer = false;
ctxDomain = GetDomainContext(
out bErrorHittingDomainServer
);
using (ctxDomain)
{
//do stuff and automatically dispose when finished
}

问题是,如果我使用相同的“GetDomainContext”函数并在“using”语句中正确返回 PrincipalContext,这是否仍然违反 Microsoft Doc 的最佳实践?

using (ctxDomain = GetDomainContext(
out bErrorHittingDomainServer
))
{
//do stuff and automatically dispose when finished
}

最佳答案

你的最后一个 block 仍然违反了所提出的建议,因为在 using 语句之后变量仍然存在(即在范围内)。试图说明的一点是,使用您的代码,您可以做到这一点:

PrincipalContext ctxDomain = null;
using (ctxDomain = GetDomainContext(
out bErrorHittingDomainServer
))
{
//do stuff and automatically dispose when finished
}

//This will throw a null reference exception at runtime
ctxDomain.DoStuff();

但是,如果您的代码是这样的:

using (PrincipalContext ctxDomain = GetDomainContext(
out bErrorHittingDomainServer
))
{
//do stuff and automatically dispose when finished
}

//This line of code won't even compile because the variable is not in scope here
ctxDomain.DoStuff();

因此在第一个 block 中,您可以在运行时 出现致命异常,但第二个 block 将永远不允许您首先进行编译。

关于c# - 从 'using' 语句中的函数返回资源实例是否与直接在 'using' 语句中实例化资源相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104100/

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