【问题标题】:"is a field but is being treated like a type" error [duplicate]“是一个字段,但被视为一种类型”错误[重复]
【发布时间】:2014-06-18 17:05:05
【问题描述】:

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

 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; }
    }
}

【问题讨论】:

  • myStructTimeAndSalesData的区别是故意的吗?
  • 您是否有一个名为myStruct 的字段,而不是一个名为myStruct 的类型?它的命名约定表明它是一个变量,而不是一个类型。
  • 您确定这是您的确切代码吗?结合错误消息,它在几个方面看起来都是错误的。
  • 至少发布有效且连贯的代码。
  • 我的原始代码不正确,它应该是:List[] myData = new List[1];

标签: c#


【解决方案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 成为字段而不是局部变量,那么您需要只需在类的顶层声明它,但在构造函数/方法中对其进行初始化。

【讨论】:

  • 谢谢,这解决了我的错误信息,现在你解释一下就很明显了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多