在 Windows 表单中使用 System.Drawing.Size 和 $button.Top & $button.Left 有什么区别?

What is the difference between using System.Drawing.Size and $button.Top & $button.Left in Windows Forms?

我一直在 Powershell 中设计一个 GUI(从没想过我会用那句话)并且,在网上查看不同的资源时,有不同的方法来定位控制项使用表格。

当我第一次开始熟悉如何构建简单表单的基本框架时,它表明:

[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
$form = New-Object System.Windows.Forms.Form

$button = New-Object System.Windows.Forms.Button
$button.Top = 30
$button.Left = 30
$form.Controls.Add($button)

但是,环顾四周,我看到大多数地方都使用这种方法:

[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')

$form = New-Object System.Windows.Forms.Form

$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Size(30,30)
$form.Controls.Add($button)

它似乎完成了完全相同的事情。

做同一件事的不同方法使编程变得有趣(无论如何对我来说)。我想知道的是,后者是否更普遍地被证明是有原因的,以及是否有原因。

谢谢。

是的,你是对的。最后是完全一样的。所有三个属性都来自 system.windows.forms.control。


Microsoft 的文档说:

Control.Left: Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its container's client area [...] The Left property value is equivalent to the Point.X property of the Location property value of the control.

Control.Top: Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its container's client area. [...] The Top property value is equivalent to the Point.Y property of the Location property value of the control.


在特定场景中使用什么取决于您。我看到的唯一真正的区别是,要设置位置,您需要一个新对象(值类型)。对于仅设置顶部或左侧,您只需要一个 [int].