如何在方法中使用`using`语句

亚尼夫·埃利亚夫(Yaniv Eliav)

我想使用该SendKeys.SendWait("{TAB}")方法,但不想在类的顶部声明它,而是在方法内部。我尝试按照以下方式进行操作,但是做错了。

using (System.Windows.Forms.SendKeys w  =  new System.Windows.Forms.SendKeys)
{
    w.SendWait("{TAB}");
}

我说错了

语句必须可以隐式转换为System.IDisposable。

从Nutshell书籍中的C#x可以很好地解释using语句:

.NET Framework为需要拆卸方法的类型定义了一个特殊的接口:

public interface IDisposable
{  
    void Dispose(); 
} 

C#的using语句提供了一个语法捷径,用于IDisposable使用一个try/finally在实现了的对象上调用Dispose

例如:

using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{  
    // ... Write to the file ... 
}

编译器将此转换为:

FileStream fs = new FileStream ("myFile.txt", FileMode.Open);
try
{  
    // ... Write to the file ... 
} 
finally
{  
    if (fs != null) ((IDisposable)fs).Dispose(); 
} 

即使在引发异常或代码提前退出该块的情况下,finally块仍可确保调用Dispose方法。

在您的情况下:

System.Windows.Forms.SendKeys不会实现IDisposable,因此您无需将其包装在using语句中,因为编译器将无法调用其Dispose方法。

长话短说。希望对您有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章