“是一个字段,但被视为类型”错误

时间:2014-06-18 17:05:05

标签: c#

我正在尝试创建一个结构列表数组。目前我会像这样初始化结构列表:

 List<myStruct> myData = new List<myStruct>();

但是当我尝试创建一个数组(例如是一个包含1个元素的数组)时,即

 List<myStruct>[] myData = new List<myStruct>[1];

 myData[0] = new List<myStruct>();

我收到错误说

  

myData是一个字段,但被视为一种类型。

我看过这个答案,但不明白区别是什么:Answer

与整数相比,C#如何处理结构有一些根本的区别吗?

感谢您的帮助。

为清楚起见,我的代码全部包含在内:

namespace My_Project
{  
    using TradingTechnologies.TTAPI;

    public partial class Form1 : Form
    {
        List<TimeAndSalesData>[] myData = new List<TimeAndSalesData>[10];
        //Here is where I believe I am making a mistake:
        myData[1] = new List<TimeAndSalesData>();
        //I get the error myData is a field but is being used as a type.


        public Form1()
        {
            InitializeComponent();
        }
    }
}
namespace TradingTechnologies.TTAPI
{
    // Summary:
    //     Represents a single trade transaction for an Instrument
    public struct TimeAndSalesData
    {
        public TimeAndSalesData(Instrument instrument, bool isOverTheCounter, Price tradePrice, Quantity tradeQuantity, TradeDirection direction, DateTime timestamp);

        // Summary:
        //     Gets the side for a trade
        public TradeDirection Direction { get; }
        //
        // Summary:
        //     Gets the Instrument associated with this trade transaction
        public Instrument Instrument { get; }
        //
        // Summary:
        //     Gets whether the trade is over-the-counter (OTC)
        public bool IsOverTheCounter { get; }
        //
        // Summary:
        //     Gets the time the trade occurred
        public DateTime TimeStamp { get; }
        //
        // Summary:
        //     Gets the price at which this trade occurred
        public Price TradePrice { get; }
        //
        // Summary:
        //     Gets the quantity traded in this trade transaction
        public Quantity TradeQuantity { get; }
    }
}

1 个答案:

答案 0 :(得分:1)

您的代码只是在类定义中浮动。它需要在某种方法或构造函数内部:

public partial class Form1 : System.Windows.Forms.Form
{
    public Form1()
    {
        InitializeComponent();

        List<TimeAndSalesData>[] myData = new List<TimeAndSalesData>[10];
        myData[1] = new List<TimeAndSalesData>();
    }
}

如果你希望myData是一个字段而不是局部变量,那么你需要在类的顶层声明它,但是在构造函数中初始化它/方法