我对C#相当陌生,在将对象添加到类中的类时遇到问题。它总是告诉我“使用'new'关键字创建对象实例”。
这是我的课程:
public class Info
{
public List<SourceInfo> sourceInfo { get; set; }
}
public class SourceInfo
{
public short id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public short subpage { get; set; }
public short xpoint { get; set; }
public short mediaPlayerId { get; set; }
public SourceInfo(short ID, string NAME, string ICON, short SUBPAGE, short XPOINT, short MEDIAPLAYERID)
{
id = ID;
name = NAME;
icon = ICON;
subpage = SUBPAGE;
xpoint = XPOINT;
mediaPlayerId = MEDIAPLAYERID;
}
这是我的代码:
Info configSelect = new Info();
private void btnSave_Click(object sender, EventArgs e)
{
try
{
configSelect.sourceInfo.Add (new SourceInfo(Convert.ToInt16(txtSrcId.Text),
txtSrcName.Text, txtSrcIcon.Text, Convert.ToInt16(txtSrcSubpage.Text),
Convert.ToInt16(txtSrcXpoint.Text), Convert.ToInt16(txtSrcMPId.Text)));
WriteFile(configSelect);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
答案 0 :(得分:1)
您的Info类需要像这样构造。寻找的“新”是您的Info类中的List sourceInfo。
public class Info
{
private List<SourceInfo> _sourceInfo = new List<SourceInfo>();
public List<SourceInfo> sourceInfo
{
get { return this._sourceInfo; }
set { this._sourceInfo = value; }
}
}