如何访问委托内的对象
我有一个函数委托返回一个对象。
我将该对象存储在列表中。
我想迭代该列表以获取对象中的值,但在 for 循环中我无法这样做:
public static class Tracking
{
public delegate TrackingObject GetTrackObject ();
public static List<GetTrackObject> TrackedLists = new List<GetTrackObject>();
public static void Register (GetTrackObject trackobject)
{
TrackedLists.Add(trackobject);
}
}
public class TrackingObject
{
object collection;
Type T;
Type K;
Type V;
public TrackingObject (object o, Type t, Type k, Type v)
{
collection = o;
T = t;
K = k;
V = v;
}
}
class TrackList<T> : List<T>
{
public string Name = null;
public int ItemCount;
public int AvgSize;
public int Size;
public TrackList (string name, byte avgsize)
{
this.Name = name;
this.AvgSize = avgsize;
this.ItemCount = this.Count;
this.Size = this.Count * this.AvgSize;
Tracking.Register(this.GetTrackObject);
}
public TrackingObject GetTrackObject ()
{
TrackingObject TO = new TrackingObject(this, typeof(T), null, null);
return TO;
}
}
public static void Main ()
{
foreach (Tracking.GetTrackObject method in Tracking.TrackedLists)
{ }
}
I have a function delegate returning an object.
I am storing that object in a list.
I want to iterate through that list to get values in object, but in for loop I am not able to do so:
public static class Tracking
{
public delegate TrackingObject GetTrackObject ();
public static List<GetTrackObject> TrackedLists = new List<GetTrackObject>();
public static void Register (GetTrackObject trackobject)
{
TrackedLists.Add(trackobject);
}
}
public class TrackingObject
{
object collection;
Type T;
Type K;
Type V;
public TrackingObject (object o, Type t, Type k, Type v)
{
collection = o;
T = t;
K = k;
V = v;
}
}
class TrackList<T> : List<T>
{
public string Name = null;
public int ItemCount;
public int AvgSize;
public int Size;
public TrackList (string name, byte avgsize)
{
this.Name = name;
this.AvgSize = avgsize;
this.ItemCount = this.Count;
this.Size = this.Count * this.AvgSize;
Tracking.Register(this.GetTrackObject);
}
public TrackingObject GetTrackObject ()
{
TrackingObject TO = new TrackingObject(this, typeof(T), null, null);
return TO;
}
}
public static void Main ()
{
foreach (Tracking.GetTrackObject method in Tracking.TrackedLists)
{ }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有将对象存储在列表中,而是将要调用(运行)的方法存储在列表中。
一种选择是调用您的方法来获取结果。
或者,您可以将列表设为对象列表,然后调用 Register 方法中的方法(并将结果存储在列表中)。
You are not storing the object in the list, you're storing the method to invoke (run) in the list.
One option is to invoke your method to get the result.
Alternatively you could make your list a list of objects, and invoke the method in your Register method (and store the result in your list).