C#条件使用块语句 [英] C# conditional using block statement
问题描述
我有以下代码,但是很尴尬.我如何更好地构建它?我必须让我的消费类实现IDisposable并有条件地构造网络访问类并在完成后处置它吗?
I have the follow code but it is awkward. How could I better structure it? Do I have to make my consuming class implement IDisposable and conditionally construct the network access class and dispose it when I am done?
protected void ValidateExportDirectoryExists()
{
if (useNetworkAccess)
{
using (new Core.NetworkAccess(username, password, domain))
{
CheckExportDirectoryExists();
}
}
else
{
CheckExportDirectoryExists();
}
}
推荐答案
One option, which is somewhat nasty but would work, based on the fact that the C# compiler calls Dispose
only if the resource is non-null:
protected void ValidateExportDirectoryExists()
{
using (useNetworkAccess
? new Core.NetworkAccess(username, password, domain)
: null)
{
CheckExportDirectoryExists();
}
}
另一种选择是编写一个静态方法,该方法返回null或NetworkAccess:
Another alternative would be to write a static method which returned either null or a NetworkAccess:
private Core.NetworkAccess CreateNetworkAccessIfNecessary()
{
return useNetworkAccess
? new Core.NetworkAccess(username, password, domain)) : null;
}
然后:
protected void ValidateExportDirectoryExists()
{
using (CreateNetworkAccessIfNecessary())
{
CheckExportDirectoryExists();
}
}
再次,我仍然不确定我是否不喜欢原始图案……这实际上取决于您需要这种模式的频率.
Again, I'm still not sure I don't prefer the original... it really depends on how often you need this pattern.
这篇关于C#条件使用块语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!