Is there a way to get the last element in a Queue?

前端 未结 5 1392
鱼传尺愫
鱼传尺愫 2021-01-26 18:26

I know stack is best and easiest way, yet could it be possible to obtain the last element in a queue without having to dequeue anything?

5条回答
  •  天涯浪人
    2021-01-26 19:02

    If you really need to you can use this but consider using a different data structure:

    public static class QueueExtensions
    {
        const BindingFlags _flags = 
            BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance;
    
        private static readonly FieldInfo _array =
            typeof(Queue).GetField("_array", _flags);
    
        private static readonly FieldInfo _size = 
            typeof(Queue).GetField("_size", _flags);
    
        public T LastItem(this Queue value)
        {
            if (value == null) 
                throw new ArgumentNullException("value");
            if (value.Count == 0) 
                throw new ArgumentException("The queue cannot be empty.", "value");
            var array = (T[])_array.GetValue(value);
            var size = (int)_size.GetValue(value);
            return array[size - 1];
        }
    }
    

提交回复
热议问题