无法使用集合初始值设定项初始化类型,因为它不实现可永久化

时间:2014-06-10 13:02:30

标签: c# .net ienumerable

我是一名相当初级的C#开发人员,所以请原谅我这很容易,但我在下面这段代码中收到此错误“invalid initializer member declarator”:

foreach (DataRow p in data.Rows)
{
  DBTrack top = new DBTrack()
 /* ===> Error starts here */   {
     track.TrackID = SQLDataHelper.GetGuid(dataReader, "TrackID"); 
     track.TrackName = SQLDataHelper.GetString(dataReader, "TrackName");
     track.ArtistName = SQLDataHelper.GetString(dataReader, "ArtistName");
     track.AddedDate = SQLDataHelper.GetDateTime(dataReader, "AddedDate");
    };

 DBTrackData.Add(top);
}

有人可以解释这意味着什么,我该如何解决并实现它以显示数据?

以下是您检查的完整方法:

 public static List<DBTrack> GetAllTracksFromReaderDB(IDataReader dataReader)
 {
  if (DBTrackData == null)
  {
     DBTrack track = new DBTrack();
     System.Data.DataTable data = new System.Data.DataTable();
     List<DBTrack> daa = new List<DBTrack>();
     DBTrackData = new List<DBTrack>();

     foreach (DataRow p in data.Rows)
     {

     DBTrack top = new DBTrack()
     /* ===> Error starts here */   {
     track.TrackID = SQLDataHelper.GetGuid(dataReader, "TrackID"); 
     track.TrackName = SQLDataHelper.GetString(dataReader, "TrackName");
     track.ArtistName = SQLDataHelper.GetString(dataReader, "ArtistName");
     track.AddedDate = SQLDataHelper.GetDateTime(dataReader, "AddedDate");
     };

    DBTrackData.Add(top);

    }
  }
  return DBTrackData;

 }

编辑:

public Guid TrackID { get; set; }
public string TrackName { get; set; }
public string ArtistName { get; set; }
public DateTime AddedDate { get; set; }

任何帮助都会很棒:)谢谢

1 个答案:

答案 0 :(得分:4)

您的语法对于成员初始化无效。您无法实例化top并尝试填充track属性。

它应该是这样的:

DBTrack top = new DBTrack
{
   TrackID = SQLDataHelper.GetGuid(dataReader, "TrackID"),
   TrackName = SQLDataHelper.GetString(dataReader, "TrackName"),
   ArtistName = SQLDataHelper.GetString(dataReader, "ArtistName"),
   AddedDate = SQLDataHelper.GetDateTime(dataReader, "AddedDate")
};