我应该把这个using语句放在哪里呢?

本文关键字:在哪里 语句 using 我应该 | 更新日期: 2023-09-27 17:49:18

我正在使用System.DirectoryServices,我有以下方法,我用来创建DirectoryEntry:

static DirectoryEntry CreateDirectoryEntry(string connectionPath)
{
    DirectoryEntry ldapConnection = null;
    try
    {
        ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME))
        ldapConnection.Path = connectionPath;
        ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Exception Caught in createDirectoryEntry():'n'n" + ex.ToString());
    }
    return ldapConnection;
} 

这个方法被这样调用:

DirectoryEntry ldapConnection = CreateDirectoryEntry("LDAP://OU=Example,DC=domain,DC=com");

我读到对于任何实现IDisposable的东西使用using语句是最佳实践。我的问题是,我是否需要在CreateDirectoryEntry()方法中使用using语句,或者我是否应该为每次调用都这样做?

为了说明我的意思,这足够吗?:

static DirectoryEntry CreateDirectoryEntry(string connectionPath)
{
    DirectoryEntry ldapConnection = null;
    try
    {
        using (ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME))
        {
            ldapConnection.Path = connectionPath;
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Exception Caught in createDirectoryEntry():'n'n" + ex.ToString());
    }
    return ldapConnection;
} 
或者我还需要像这样在调用上使用using语句吗?:
using (DirectoryEntry ldapConnection = CreateDirectoryEntry("LDAP://OU=Example,DC=domain,DC=com"))
{
    //Do something with ldapConnection
}

任何帮助都非常感谢!

注意:我不能使用System.DirectoryServices.AccountManagement解决这个问题,所以请保留与System.DirectoryServices相关的答案。谢谢!

我应该把这个using语句放在哪里呢?

您的最后一个代码片段是正确的,否则您将向调用者返回一个已处理的ldapConnection—这不是一件好事。

+1表示使用using!!

您的第一个代码片段将在返回ldapConnection之前对其进行处理,因此返回一个您显然不需要的已处理对象。

你的函数应该看起来像这样:

static DirectoryEntry CreateDirectoryEntry(string connectionPath)
{
    DirectoryEntry ldapConnection = null;
    try
    {
        ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME)
        ldapConnection.Path = connectionPath;
        ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Exception Caught in createDirectoryEntry():'n'n" + ex.ToString());
    }
    return ldapConnection;
} 
虽然第二个代码片段是正确的:为了正确地处理DirectoryEntry,您应该使用using