Considering the follow code can someone explain to me why and why not to use 'using'? I've read about the rule of thumb with IDisposable but why is IDisposable the determining factor?

private string GetWMIProperty(string property)
{
string value = string.Empty;
SelectQuery selectQuery = new SelectQuery("Win32_OperatingSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery))
{

  foreach (ManagementObject mo in searcher.Get())
   {
     value = mo[property].ToString();
  }
}
return value;
}
有帮助吗?

解决方案

using translates into try-finally block. So even in case of exception it will call Dispose method of the enclosing object.

See: using Statement (C# Reference)

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

其他提示

It's not the determining factor necessarily. IDisposable merely requires the object to implement void Dispose(). In fact, many objects that implement IDisposable don't even really do anything when "disposed." You'll have to read documentation or look at decompiled code in each case to determine if it's worth it to dispose of objects, whether with a using or a call to Dispose().

To more directly answer your question, you would want to use using if disposing the object in question cleans up some resource (open files, database connections, etc.).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top