【问题标题】:Constructor to allocate my own array<T> class构造函数来分配我自己的 array<T> 类
【发布时间】:2012-03-30 06:41:16
【问题描述】:

我有一个像 Quete 这样的课程(先进先出)

public class Tor<T>
{
    private T[] elements;

    private int next;

    public event EventHandler<EventArgs> queueFull;   
}

我需要构建一个 Constructor 来获取一个参数(队列大小(int)。它分配数组并初始化变量,

怎么做?

【问题讨论】:

  • 我猜你之前是个c++程序员:)

标签: c# asp.net visual-studio-2010


【解决方案1】:

那么简单

public Tor(int size)
{
  elements = new T[size];
}

【讨论】:

  • 来自问题allocate the arrary and initilizes the variable
【解决方案2】:
public class Tor<T> where T : new()
{
    public Tor(int size)
    { 
        elements = new T[size];
        for (int i = 0; i < size; i++)
        {
            elements[i] = new T();
        }
    }

    private T[] elements;

    private int next;

    public event EventHandler<EventArgs> queueFull;   
}

public class Tor<T> where T : new()
{
    public Tor(int size)
    { 
        elements = Enumerable.Range(1,size).Select (e => new T()).ToArray(); 
    }
    ...
}

【讨论】:

    【解决方案3】:
    public class Tor<T>
    {
        private T[] elements;
    
        private int next;
    
        public event EventHandler<EventArgs> queueFull;
    
        public Tor(int capacity)
        {
            elements = new T[capacity];
        }
    }
    

    应该这样做。

    【讨论】:

      【解决方案4】:
      public class Tor<T>
      {
          private T[] elements;
      
          private int next;
      
          public event EventHandler<EventArgs> queueFull;
      
          public Tor(int size)
          {
              if (size < 0)
                  throw new ArgumentOutOfRangeException("Size cannot be less then zero");
      
              elements = new T[size];
              next = 0;
          }
      }
      

      【讨论】:

        【解决方案5】:

        考虑使用现有的类

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-30
          • 1970-01-01
          • 1970-01-01
          • 2022-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多