正确使用范围

Kon*_*ten 3 c# scope using-statement

我正和一位同事讨论使用声明的适当范围.这是有问题的方法.

public Guid IsServerReachable()
{
  try
  {
    WhoAmIResponse whoAmI;
    using (OrganizationServiceProxy service = GetService())
      whoAmI = service.Execute(new WhoAmIRequest()) as WhoAmIResponse;
    return whoAmI.UserId;
  }
  catch { return Guid.Empty; }
}
Run Code Online (Sandbox Code Playgroud)

我们中的一个人声称using语句应该包含whyAmI的声明,而另一个声明它只是需要使用ified服务实例.我不是说我的理论是哪一个,但显然是错误的.哪一个?

Tho*_*mar 6

两者都是正确的.我倾向于写这个:

public Guid IsServerReachable()
{
    try
    {
        using (OrganizationServiceProxy service = GetService())
        {
            WhoAmIResponse whoAmI = service.Execute(new WhoAmIRequest()) as WhoAmIResponse;
            return whoAmI.UserId;
        }
    }
    catch { return Guid.Empty; }
}
Run Code Online (Sandbox Code Playgroud)

这对是否whoAmI被处置没有任何影响- 唯一被自动处理的是service.

如果WhoAmIResponse也是IDisposable,您必须编写以下内容以自动释放两者:

    using (OrganizationServiceProxy service = GetService())
    using (WhoAmIResponse whoAmI = service.Execute(new WhoAmIRequest()) as WhoAmIResponse)
        return whoAmI.UserId;
Run Code Online (Sandbox Code Playgroud)