列表IEnumerable 类中的委托数
我有一个用户定义的类,我想创建一个公共列表作为其中的一部分。我希望列表成为委托函数列表,我可以添加该列表并将每个列表成员设置为委托函数。我希望这个函数列表成为我实例化的类的一部分,因此当我将其传递给其他函数时,它遵循类的实例。我需要能够通过 foreach 循环调用委托函数,因此它也必须是 IEnumberable。
我已经尝试了几个小时,我所拥有的可能会或可能不会完成部分工作。当我开始看起来需要为自定义列表编写自己的 IEnumberation 例程时,我意识到我有点不知所措,于是来到这里。
这是我的代码:
public delegate List<ChartTestModel> MyDelegate<T>(T i);
public class DelegateList<T>
{
public void Add(MyDelegate<T> del)
{
imp.Add(del);
}
public void CallDelegates(T k)
{
foreach (MyDelegate<T> del in imp)
{
del(k);
}
}
private List<MyDelegate<T>> imp = new List<MyDelegate<T>>();
}
我什至不知道这是否达到了我想要的效果。但我知道我不能通过它 ForEach 。它完全是根据在 Google 上查找的代码拼凑而成的。我几乎不明白它应该做什么。
I have a user defined class that I want to create a public List as part of. I want the List to be a List of delegate functions that I can add to and set each List Member to a delegate function. I want this list of functions to be part of the class I instantiate, so it follows the instance of the class as I pass it to other functions. I need the ability to call the delegated functions via a foreach loop, so it also has to be IEnumberable.
I've been trying for several hours, what I have may or may not do part of the job. When it started looking like I needed to write my own IEnumberation routines for the custom List, I realize I was in way over my head and came here.
This is the code I have:
public delegate List<ChartTestModel> MyDelegate<T>(T i);
public class DelegateList<T>
{
public void Add(MyDelegate<T> del)
{
imp.Add(del);
}
public void CallDelegates(T k)
{
foreach (MyDelegate<T> del in imp)
{
del(k);
}
}
private List<MyDelegate<T>> imp = new List<MyDelegate<T>>();
}
I don't even know if this does what I want it to or not. I know I can't ForEach through it, though. It's written entirely from pieced together code from looking on Google. I barely understand what it's supposed to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我根本不明白为什么你需要一个自定义类。只需使用
List
,其中 T 是任何委托类型。I don't see why you need a custom class at all. Just use
List<T>
where T is whatever delegate type.IEnumerable
实现起来很简单,特别是当您有一个集合作为类的成员时。您需要做的就是定义适当的 GetEnumerator 方法,最简单的事情就是返回底层集合的枚举器。在这里,您为
IEnumerable
隐式实现方法,并为IEnumerable
显式实现方法。 (您必须实现两者,因为IEnumerable
继承IEnumerable
。)对于您的特定类,您可能有
IEnumerable<T>
is simple to implement, particularly when you have a collection as a member of the class. All you need to do is define appropriateGetEnumerator
methods, and the easiest thing to do is return the enumerator of the underlying collection.Here, you implement methods for implicitly for
IEnumerable<T>
and explicitly forIEnumerable
. (You have to implement both asIEnumerable<T>
inheritsIEnumerable
.)For your specific class, you might have
我希望这对您有用。
I hope this is userful to you.