【问题标题】:structs in C# and constructorsC# 中的结构和构造函数
【发布时间】:2012-02-27 13:48:47
【问题描述】:

我有理想情况下想要表示的数据:

LinkedList<T>[]

但是,你不能在泛型上这样做,所以我将它包装在一个结构中:

    public struct SuitList                      
    {
        LinkedList<T> aList;

        public SuitList()
        {
            aList = new LinkedList<T>();
        }
    }

现在,在我的课堂上,我有

   SuitList[] myStructList;      //there is only 4 indices of myStructList

如何在类的构造函数中初始化 aList?我尝试如下:

myStructList = new SuitList[4];

for(int i = 0; i < 4; i++)
{
    myStructList[i] = new SuitList();
}

编译器给了我一个错误,说结构不能包含显式无参数构造函数。有没有更好的方法来做到这一点? 提前感谢您的帮助。

【问题讨论】:

  • 这听起来很奇怪。为什么需要一个链表数组?
  • 当您尝试使用LinkedList&lt;T&gt;[] 时收到什么错误?它没有任何问题。
  • @phoog,你是对的。我错了
  • @Slaks,我的数组包含 4 个链表,其中每个链表都有一个共同的索引属性。因此,我可以方便地访问具有指定属性的每个列表。

标签: c# arrays constructor struct initialization


【解决方案1】:

C# 不是 Java。
你可以用泛型做到这一点。

要回答您的问题,您应该创建一个类,而不是一个结构。

【讨论】:

    【解决方案2】:

    你可以做到这一点,而不必是一个类。

    public struct SuitList<T>
        {
            LinkedList<T> aList;
    
            public SuitList(int nothing = 0)
            {
                aList = new LinkedList<T>();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2017-07-25
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多