c# list 无法将字符串转换为日期时间并将字符串转换为整型

本文关键字:转换 字符串 日期 时间 整型 list string | 更新日期: 2023-09-27 18:08:39

public UserAccount(List<string> data)
{
    this.UserIDNumber = data[0]; //issue here
    this.name = data[1];
    this.Username = data[2];
    this.Password = data[3];
    this.Birthday = data[4]; //issue here
    this.Address = data[5];
    this.City = data[6];
}

我遇到的问题是我无法转换两个数据类型。如果我用this.Birthday.Tostring()this.UserIDNumber.ToString()

我得到错误:赋值的左边必须是var、prop或indexer

c# list <string>无法将字符串转换为日期时间并将字符串转换为整型

您需要显式地将字符串转换为正确的类型。

public UserAccount(List<string> data)
{
    this.UserIDNumber = Convert.ToInt32(data[0]); 
    this.name = data[1];
    this.Username = data[2];
    this.Password = data[3];
    this.Birthday = DateTime.Parse(data[4]); 
    this.Address = data[5];
    this.City = data[6];
}

或者更安全的方法是,如果转换失败,不会抛出异常。但是请记住,如果你不处理默认值,你可能会得到损坏的数据。

public UserAccount(List<string> data)
{
    int id;
    this.UserIDNumber = int.TryParse(data[0], out id) ? id : 0; 
    this.name = data[1];
    this.Username = data[2];
    this.Password = data[3];
    DateTime date;
    this.Birthday = DateTime.TryParse(data[4], out date) ? date : DateTime.MinValue; 
    this.Address = data[5];
    this.City = data[6];
}

试试这个:

 this.UserIDNumber = Convert.ToInt32(data[0]);
 this.Birthday = DateTime.Parse(data[4]);

我最后做了什么(对于这个和datetime)

this.ErrorMessage = string.Empty;
  int parseInt = 0;
  if (!int.TryParse(data[0], out parseInt))
  {
    this.ErrorMessage += "Error Parsing the account number! data was: " + data[0];
    this.AcctNumber = -1;
  }
  else
  {
    this.AcctNumber = parseInt;
  }