如何使这个方法可重用?

use*_*079 0 c# reusability

我已将此方法复制粘贴到两个类中.我宁愿在第一堂课中重复使用它.这是在Windows窗体应用程序中.

public void defineMapArea()
{
    PictureBox pictureBox1 = new PictureBox();

    // Dock the PictureBox to the form and set its background to white.
    pictureBox1.Dock = DockStyle.Fill;
    pictureBox1.BackColor = Color.White;

    // Connect the Paint event of the PictureBox to the event handler method.
    pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);

    // Add the PictureBox control to the Form. 
    this.Controls.Add(pictureBox1);
}
Run Code Online (Sandbox Code Playgroud)

在方法中从一个类到另一个类需要改变的唯一事情是"this"关键字引用类,因为悬停在"this"上确认.我想也许"this"只适用于调用方法的类,但我认为它仍然引用了定义方法的类.简单地将类作为参数传递会很棒,但我在思考这不起作用,因为我尝试过.

任何帮助赞赏.谢谢!

Ale*_*ria 5

我会这样做:

public static void DefineMapArea(Form form, Action<object, PaintEventArgs> handler)
{
    if (form == null)
    {
        throw new ArgumentNullException("form");
    }

    if (handler == null)
    {
        throw new ArgumentNullException("handler");
    }

    PictureBox pictureBox1 = new PictureBox();

    // Dock the PictureBox to the form and set its background to white.
    pictureBox1.Dock = DockStyle.Fill;
    pictureBox1.BackColor = Color.White;

    // Connect the Paint event of the PictureBox to the event handler method.
    pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(handler);

    // Add the PictureBox control to the Form. 
    form.Controls.Add(pictureBox1);
}
Run Code Online (Sandbox Code Playgroud)

你可以打电话给它(假设你的表格):

DefineMapArea(this, (sender, e) =>
{
    // ... put here your code
});
Run Code Online (Sandbox Code Playgroud)

要么

DefineMapArea(this, Handler);

void Handler(object sender, PaintEventArgs e)
{
    // ... put here your code
}
Run Code Online (Sandbox Code Playgroud)