有没有办法让逗号与对象分开。请注意其对象不是对象列表
例如:
public class EmployeeLogReportListViewModel
{
public DateTime Date { get; set; }
public int EmployeeID { get; set; }
public TimeSpan Time { get; set; }
public int Sort { get; set; }
public string Employer { get; set; }
}
具有以下值
Date = "2018/02/03"
EmployeeID = 111
Time = 11:53 AM
Sort = 1
Employer = EMP
这应该导致
2018/02/03,111,11:53 AM,1 EMP
做到这一点的最佳方法是什么?可能的单行代码导致我不想使用字符串构建器并附加所有这些。
接受挑战
var o = new EmployeeLogReportListViewModel();
var text = string.Join
(
",",
typeof(EmployeeLogReportListViewModel)
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select
(
prop => prop.GetValue(o).ToString()
)
);
Console.WriteLine(text);
从技术上讲,这是一条线。
我认为你正在寻找覆盖.ToString()
方法。你必须像这样修改类:
public class EmployeeLogReportListViewModel
{
public DateTime Date { get; set; }
public int EmployeeID { get; set; }
public TimeSpan Time { get; set; }
public int Sort { get; set; }
public string Employer { get; set; }
public override string ToString()
{
return String.Format("{0},{1},{2},{3},{4}", this.Date, this.EmployeeID, this.Time, this.Sort, this.Employer);
}
}
EmployeeLogReportListViewModel objVm = new EmployeeLogReportListViewModel();
// Assign values for the properties
objVm.ToString(); // This will give you the expected output