如何访问委托内的对象

时间:2011-09-01 10:39:20

标签: c# delegates

我有一个函数委托返回一个对象 我将该对象存储在列表中 我想遍历该列表以获取对象中的值,但是在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)
    { }
}

1 个答案:

答案 0 :(得分:1)

您没有将对象存储在列表中,而是存储要在列表中调用(运行)的方法。

一个选项是调用您的方法来获得结果。

public static void Main ()
{
    foreach (Tracking.GetTrackObject method in Tracking.TrackedLists)
    {
        object trackedObject = method();
    }
}

或者,您可以使列表成为对象列表,并在Register方法中调用该方法(并将结果存储在列表中)。