gpt4 book ai didi

c# - 如何为多个类似控件编写事件处理程序?

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:14 25 4
gpt4 key购买 nike

基本上我有一些控件,它们做类似的事情,但不同的控件使用不同的值。例如:

public static void DeleteItemsFromList ( object sender, EventArgs e )
{
ListBox control = null;
switch ( ( ( Button ) sender ).Name )
{
case "EffectsRemove": control = ( ListBox ) ActiveForm [ "EffectsList" ]; break;
case "LayersRemove": control = ( ListBox ) ActiveForm [ "LayersList" ]; break;
case "ObjectsRemove": control = ( ListBox ) ActiveForm [ "ObjectsList" ]; break;
}

control.Items.Add ( ( ( Button ) sender ).Name )

string action = null;
switch ( ( ( CheckButton ) sender ).Name )
{
case "EffectsRemove": action = "Effects"; break;
case "LayersRemove": action = "Layers"; break;
case "ObjectsRemove": action = "Objects"; break;
}

var selectedItem = control.SelectedItem;
if ( selectedItem == null )
return;

Refresh = false;
UpdateUI ( action );
Refresh = true;
}

这是不好的做法吗?有没有更好的方法来基于类似行为的控件来执行这些类型的可变事件处理程序?

最佳答案

就我个人而言,我发现您的示例留下了太多出错的机会。最好的办法是将通用功能提取到一个单独的方法中。

public static void EffectsRemove_Click(object sender, EventArgs e)
{
DeleteItemsFromList(
(Button)sender,
(ListBox)ActiveForm["EffectsList"],
"Effects");
}

public static void LayersRemove_Click(object sender, EventArgs e)
{
DeleteItemsFromList(
(Button)sender,
(ListBox)ActiveForm["LayersList"],
"Layers");
}

public static void ObjectsRemove_Click(object sender, EventArgs e)
{
DeleteItemsFromList(
(Button)sender,
(ListBox)ActiveForm["ObjectsList"],
"Objects");
}

public static void DeleteItemsFromList(
Button sender,
ListBox control,
string action)
{
control.Items.Add(sender.Name);

var selectedItem = control.SelectedItem;
if ( selectedItem == null )
return;

Refresh = false;
UpdateUI action;
Refresh = true;
}

关于c# - 如何为多个类似控件编写事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938238/

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