对象以逗号分隔的字符串

Sec*_*der 1 c# string

有没有办法让逗号与对象分开.请注意其对象不是对象列表

例如:

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; }
}
Run Code Online (Sandbox Code Playgroud)

具有以下值

Date = "2018/02/03"
EmployeeID = 111
Time = 11:53 AM
Sort = 1
Employer = EMP
Run Code Online (Sandbox Code Playgroud)

这应该导致

2018/02/03,111,11:53 AM,1 EMP
Run Code Online (Sandbox Code Playgroud)

做到这一点的最佳方法是什么?可能的单行代码导致我不想使用字符串构建器并附加所有它.

suj*_*lil 7

我认为你正在寻找Overridden .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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

EmployeeLogReportListViewModel objVm = new EmployeeLogReportListViewModel();
// Assign values for the properties
objVm.ToString(); // This will give you the expected output
Run Code Online (Sandbox Code Playgroud)

  • 字符串插值也可以在 C# 6 中使用。 (2认同)

Joh*_* Wu 6

接受挑战

var o = new EmployeeLogReportListViewModel();
var text = string.Join
(
    ",",
    typeof(EmployeeLogReportListViewModel)
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Select
        (
            prop => prop.GetValue(o).ToString()
        )
);
Console.WriteLine(text);
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这是一行。