gpt4 book ai didi

C#创建绘图对象

转载 作者:行者123 更新时间:2023-11-30 14:53:02 24 4
gpt4 key购买 nike

以下代码是来自MSDN的示例:

private void Form1_Paint(object sender, 
System.Windows.Forms.PaintEventArgs pe)
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
}

我有一些问题:

  • 我们可以更改Form1_Paint 方法的名称吗?我的意思是它必须有“Paint”后缀吗? .net什么时候调用这个方法?框架如何知道要调用哪个方法才能绘制图像?

  • 我不明白我们为什么只定义 Form1_Paint 方法可以接收 2 个参数,然后神奇地框架只调用该方法并引用 object 和对 PaintEventArgs 对象 (pe) 的引用。

对于愚蠢的问题,我很抱歉,但我主要来自函数式编程,我对使用框架感到困惑,因为它们似乎在调用自己的方法。有人可以向 6 岁的 child 解释一下吗?

最佳答案

根据评论,Form1_PaintPaint 事件的事件处理程序。

参数不是魔术,它们是此事件所必需的 - 即如果您想绑定(bind)到此事件,您的处理程序方法实现必须匹配它所需的事件参数。 PaintEventHandler 定义为:

public delegate void PaintEventHandler(object sender, PaintEventArgs e);

默认情况下,当您在设计器中添加处理程序时(例如,通过双击 UI 控件或“闪电”选项卡下的 Events 图标),会自动创建一个事件处理程序使用默认名称:

{name of the control}_{name of event}

在您的例子中,您的表单在创建处理程序方法时具有名称 Form1

您可以重命名处理程序方法,但如果您这样做,您还需要更改 Form1.designer.cs 中的相应事件绑定(bind)(即更改 this.Form1_Paint 在下面):

this.Name = "Form1";
this.Text = "Form1";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);

(+=表示订阅事件——一旦订阅,当事件被引发时,所有的订阅方法都会被调用)

编辑

由于您来自 FP 背景,您可能对不需要显式命名的事件处理程序感兴趣,您还可以订阅适当类型的 lambda:

this.Paint += (sender, pe) => 
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
};

其中 senderpe 的类型与之前完全相同。默认情况下,设计器不会执行此操作,因此您可以通过编程方式将上述订阅添加到您的 Form1 构造函数

关于C#创建绘图对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com