在C#中使用using语句设置成员。

huangapple go评论74阅读模式
英文:

C# setting members from using statement

问题

当 Y 被处理时,PropertyX 会继续引用之前与 Y 关联的对象。在第一个代码示例中,当 using 块结束时,DisposableType 对象 y 被处理,但 PropertyX 仍然引用 y.GetX() 返回的值。在第二个代码示例中,Y 被处理时,Dispose 方法将调用 Y.Dispose(),并确保与 Y 关联的资源被释放,然后 PropertyX 会引用 null 或默认值,具体取决于 TypeX 的数据类型。

英文:
class A
{
  TypeX PropertyX;

  void SomeMethod()
  {
    using (DisposableType y = new DisposableType())
    {
      PropertyX = y.GetX();
    }
  }
}

What happens to PropertyX when Y is being disposed?
Would I rather do this, if I don't know what is being disposed with Y?

class A : IDisposable
{
  TypeX PropertyX { get; set;}
  DisposableType Y { get; set; }

  void SomeMethod()
  {
    using (Y = new DisposableType())
    {
      PropertyX = Y.GetX();
    }
  }

 void Dispose()
 {
   Y.Dispose();
 }

}

答案1

得分: 2

以下是您要翻译的内容:

Your MainWindow will not get disposed, but automation instance will get disposed after the execution leaves using block. Another way to write this would be:

using var automation = new UIA2Automation();
MainWindow = launcher.App.GetMainWindow(automation);

A more verbose way to write the same thing would be:

var automation = new UIA2Automation();
MainWindow = launcher.App.GetMainWindow(automation);

// At this point MainWindow is already instantiated.
// We no longer need automation instance so we dispose of it.
automation.Dispose();

Quick Google search lead me to FlaUI project and it looks like it is what you are using. Looking at the code samples, it looks like your approach is the correct one.

英文:

EDIT: OP changed the question

Your MainWindow will not get disposed, but automation instance will get disposed after the execution leaves using block. Another way to write this would be:

    using var automation = new UIA2Automation();
    MainWindow = launcher.App.GetMainWindow(automation);

A more verbose way to write the same thing would be:

    var automation = new UIA2Automation();
    MainWindow = launcher.App.GetMainWindow(automation);
    
    // At this point MainWindow is already instantiated.
    // We no longer need automation instance so we dispose of it.
    automation.Dispose();

Quick Google search lead me to FlaUI project and it looks like it is what you are using. Looking at the code samples, it looks like your approach is the correct one.

huangapple
  • 本文由 发表于 2023年3月1日 15:30:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定