开发者

C# - Extending the stack class - Error

I'm getting an error: "The non-generic type `System.Collections.Stack' cannot be us开发者_如何学编程ed with the type arguments"

    // For use in BONUS section of lab:
    class LossyStack<T> : Stack<T> {
 private const int getAway=1;  // Starts out at 1 (out of 20 random numbers - 5%)
    public Stack<string> escsaped;

    public LossyStack(): base() {   // Constructor
        escaped = new Stack<string>();
    }

    public T Pop() {
  RandomNumber rand = new RandomNumber(1,20);  // One to twenty 

  if (rand<=getAway){
      escaped.push(base.Pop());
  }
  else {
        return base.Pop();
  }
  getAway++; // add another 1 to getAway so it increases by 5%
    }
  }

Can anyone tell me how I'd be able to fix this? Thanks a bunch.


Replace:

using System.Collections;

with

using System.Collections.Generic;


One of the problems I see is that the "escaped" stack is of type string, and you are pushing into it from the base class of your "generic" stack.

Another problem is that "getaway" is declared as const, you won't be able to increment it in your pop method in that case.

Additional Edit here: Your Pop method does not return anything for each code path and so it won't compile. Were you intending a loop when you are pushing into the escaped stack?

I was going to try to clean it up and make something workable, but I am not sure what this is supposed to be doing. Here is some code, it still won't compile because of the code path return issue, but its cleaned up a bit:

class LossyStack<T> : Stack<T>
{
    private int getAway = 1;  // Starts out at 1 (out of 20 random numbers - 5%)
    public Stack<T> escaped = new Stack<T>();

    public LossyStack()
        : base()
    {   // Constructor
    }

    public T Pop()
    {
        Random rand = new Random();
        if (rand.Next(20) <= getAway)
        {
            escaped.Push(base.Pop());
        }
        else
        {
            return base.Pop();
        }
        getAway++; // add another 1 to getAway so it increases by 5%
    }
}


Hmmm, maybe you're needing a:

using System.Collections.Generic;

Up in your .cs file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜