简体   繁体   English

C#从另一方法调用事件(linkLabel2_LinkClicked)

[英]C# Call an event (linkLabel2_LinkClicked) from another method

I have an event handler on my form for a LinkLabel linkLabel2_LinkClicked: 我的表单上有一个用于LinkLabel linkLabel2_LinkClicked的事件处理程序:

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //code here
}

I need to call it from another method that does not have an object sender and any eventargs: 我需要从另一个没有对象发送者和任何eventargs的方法中调用它:

private void UpdateMethod()
{
    linkLabel2_LinkClicked(this, ?????)
}

If it were a Button I would just call the PerformClick method. 如果它是一个Button,我将调用PerformClick方法。 But there is no such for a LinkLabel that I could find. 但是我找不到LinkLabel。

What is the best practice to execute the code in the linkLabel2_LinkClicked event handler? linkLabel2_LinkClicked事件处理程序中执行代码的最佳实践是什么?

Update: I guess I was not clear on this. 更新:我想我对此还不清楚。 I wonder about the best practice as I have seen this approach. 我已经看到了这种方法,所以我不知道最佳实践。 I can see from the answers that this is not the correct approach but to move the code to a separate method and call it directly from the other method. 从答案中可以看出,这不是正确的方法,而是将代码移至单独的方法,然后直接从其他方法调用它。 Please let me know if any other reasoning goes with this. 请让我知道是否还有其他理由。

Update 2: I rewrote the code now as follows: 更新2:我现在将代码重写如下:

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    CreatePreview();
}

private void UpdateMethod()
{
    CreatePreview();
}

private void CreatePreview()
{
    //code comes here
}

It works perfectly. 它运作完美。

You can put null in event parameter : 您可以在事件参数中添加null:

linkLabel2_LinkClicked(this, null);

or create a new event object : 或创建一个新的事件对象:

linkLabel2_LinkClicked(this, new LinkLabelLinkClickedEventArgs());

But the best way is create a separate methode and call it in every time you need it. 但是最好的方法是创建一个单独的方法,并在每次需要时调用它。

You could just pass null since you're not using the parameter anyway, but I'd recommend against that. 您可以只传递null因为无论如何您都不使用该参数,但我建议您不要这样做。 It's discouraged to call an event directly, and it leads to code that's tough to read. 不建议直接调用事件,这会导致难以阅读的代码。

Just have the other method call CreatePreview() . 只需让另一个方法调用CreatePreview()

private void UpdateMethod()
{
    CreatePreview();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM