开发者

How to access object inside delegate

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开发者_Go百科 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)
    { }
}


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.

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

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜