【问题标题】:Can someone explain --> private BrowserWindow mParentWindow { get; set; }有人可以解释一下 --> private BrowserWindow mParentWindow { get;放; }
【发布时间】:2015-02-15 20:39:05
【问题描述】:

有人可以在下面的代码中解释我吗?基本上它是什么,它在做什么,为什么我需要 mParentWindow?我不能只用 ParentWindow 来做吗

private BrowserWindow mParentWindow { get; set; }
public BrowserWindow ParentWindow { 
   get {
      if (this.mParentWindow == null) {
        this.mParentWindow = TopParentWindow();
      }
      return this.mParentWindow;
   }
}

【问题讨论】:

  • 什么需要解释......你是认真的你不理解你发布的代码......?这是一个开始学习的好地方C# Basics Tutorial - Properties
  • 你了解Property 是什么吗?你认为这里发生了什么?很高兴您带着要解决的问题来到 c#,但最好在提出问题之前先阅读基本的 c# 教程。
  • 延迟初始化 - 它确保无论您阅读 .ParentWindow 多少次,检索它的进程 (TopParentWindow()) 只被调用一次,第一次需要它。
  • 我只是困惑为什么我需要另一个属性“mParentWindow”来简单地获取 BrowserWindow。我想我应该这样做 code public BrowserWindow ParentWindow { get { if (this.ParentWindow == null) { this.ParentWindow = TopParentWindow(); } 返回 this.ParentWindow; } }
  • mParentWindow 不是属性,而是字段。按照链接。

标签: c# coded-ui-tests


【解决方案1】:

基本上,您可以将mParentWindow 设置为public 并删除m。您提供的这段代码在类中创建了一个只读属性。您添加了一个private BrowserWindow,您可以在它所属的类中随意更改它,但不能在它之外访问或更改它。然后,您拥有可以从其父类外部访问但不能更改的只读属性。 我将尝试在下面更好地解释这一点:

private BrowserWindow mParentWindow { get; set; }

这一行创建了一个BrowserWindow 类的实例,由于get 函数的存在,它可以被访问和更改,但只能在父类内部,因为它是private

public BrowserWindow ParentWindow
{ 
    get
    {
        if (this.mParentWindow == null)
        {
            this.mParentWindow = TopParentWindow();
        }
        return this.mParentWindow;
    } 
}

这段代码创建了BrowserWindow 类的实例,该实例可以访问但不能更改,因为存在get 函数但没有set 函数。这可以在课堂外访问,因为它是public。 在get 函数内部,代码表示如果之前没有设置mParentWindow 的值,请将其设置为TopParentWindow 函数的结果。 在此之后它返回 mParentWindow 的值。

【讨论】:

  • 示例中的属性应公开以匹配描述。此外,与 OP 发布的代码的主要处理是延迟初始化,此处未提及。第一段很清楚地描述了该属性(减去懒惰),但是,写得很好。
  • 我在完成之前不小心按了回车键。
  • 谢谢大家和@Rariolu ...我现在很好。它回答了我一直在寻找的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2016-12-12
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
相关资源
最近更新 更多