gpt4 book ai didi

c# - 将扩展方法中的事件和函数分配为参数

转载 作者:行者123 更新时间:2023-12-04 04:13:07 25 4
gpt4 key购买 nike

我有一个对象列表,我想在工厂方法中分配值。我检查了类似问题 但他们可以访问 中的方法现有组件 .我想使用自定义方法并定义应该设置哪个事件。

例如

mylist.Assign(nameofevent,assignfuntion);

用法类似
public static void Assign(this Control[] controls,eventhandler @event,Action func)
{
foreach (var item in controls)
//assign function to event
item.clicked += func;//Preferably clicked must be Specified from argument
}

最佳答案

试图帮助了解 Shervin Ivari 的问题有什么问题。我正在说明如何实现它。但仍然不确定这是否是您想要的?

public static void Main()
{
var listeners = new List<SomeClassWithListener>
{
new SomeClassWithListener(),
new SomeClassWithListener(),
new SomeClassWithListener()
};

var theEvent = new SomeClassWithEvent();

MatchEmUp(listeners, theEvent);

theEvent.RaiseEvent();
}

public static void MatchEmUp(IEnumerable<SomeClassWithListener> listeners, SomeClassWithEvent theEvent)
{
foreach(SomeClassWithListener listener in listeners)
theEvent.ItsAlive += listener.ThenIllSlayIt;
}

public class SomeClassWithListener
{
public void ThenIllSlayIt(object sender, EventArgs e)
{
Console.WriteLine("Chaaaaaarge!");
}
}

public class SomeClassWithEvent
{
public EventHandler ItsAlive;

public void RaiseEvent()
{
ItsAlive.Invoke(this, new EventArgs());
}
}

https://dotnetfiddle.net/4Y13cf

或者通过使用委托(delegate),EventHandler 也是一个委托(delegate):
public static void Main()
{
var listener1 = new SomeClassWithListener();
var listener2 = new SomeClassWithListener();
var listener3 = new SomeClassWithListener();

var listeners = new List<EventHandler>
{
listener1.ThenIllSlayIt,
listener2.ThenIllSlayIt,
listener3.ThenIllSlayIt
};

var theEvent = new SomeClassWithEvent();

MatchEmUp(listeners, theEvent);

theEvent.RaiseEvent();
}

public static void MatchEmUp(IEnumerable<EventHandler> listeners, SomeClassWithEvent theEvent)
{
foreach(EventHandler listener in listeners)
theEvent.ItsAlive += listener;
}

public class SomeClassWithListener
{
public void ThenIllSlayIt(object sender, EventArgs e)
{
Console.WriteLine("Chaaaaaarge!");
}
}

public class SomeClassWithEvent
{
public EventHandler ItsAlive;

public void RaiseEvent()
{
ItsAlive.Invoke(this, new EventArgs());
}
}

https://dotnetfiddle.net/k16lsy

关于c# - 将扩展方法中的事件和函数分配为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61357837/

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