【问题标题】:Having trouble adding custom class to list (C#)将自定义类添加到列表时遇到问题(C#)
【发布时间】:2012-10-31 14:48:19
【问题描述】:

我希望我的术语在这里是正确的,仍然学习所有正确的术语。

我使用以下代码创建了一个自定义类:

    public class inputData
{
    public string type;
    public int time;
    public int score;
    public int height;
}

我想创建一个包含该类的列表,就像我在这里所做的那样:

List<inputData> inputList = new List<inputData>();

我现在正在尝试添加到该列表,但遇到了问题。我已经尝试了以下两种方法,但仍然没有运气。有人可以在这里指出我正确的方向吗?

inputList.Add(new inputData("1", 2, 3, 4));

inputList.type.Add("1"); 

【问题讨论】:

    标签: c# list class


    【解决方案1】:

    你需要object initializer

    改变

    inputList.Add(new inputData("1", 2, 3, 4));
    

    收件人

    inputList.Add(new inputData{type="1", time=2, score=3, height=4});
    

    【讨论】:

    • 非常感谢!效果很好——我以为我已经很接近了,只是语法不太正确。
    • 谢谢,是的,根据弹出窗口,我不得不“等待 10 分钟”。
    【解决方案2】:

    问题不在于列表,而在于 inputData 类 - 您正在尝试使用未定义的构造函数。将构造函数添加到 inputData 类中:

    public inputData(string type, int time, int score, int height)
    {
      this.type=type; this.time=time, this.score=score, this.height=height
    }
    

    其次,遵循 C# 约定 - 类名应以大写开头,公共字段替换为 C# 属性。但这不是您的代码不起作用的问题。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多