我想知道是否可以在public override string ToString()
方法中显示List,所以当我列出所有属性时,我也可以看到List<>
的每个元素。
这是我的ToString()
方法:
public override string ToString()
{
return this.Employees; //Here would be the list
}
这将是具有我希望列出的属性的Employees的构造函数。 例如:员工:John Doe,员工:Brian Johnson,员工:Eric Dunn。
public Employee(string fullname)
{
this.FullName = fullname;
}
答案 0 :(得分:2)
public override string ToString()
{
StringBuilder t = new StringBuilder();
foreach(Employee e in this.Employees)
t.AppendLine (string.Format ("Employee: {0}",e.Fullname));
return t.ToString ();
}
或
public override string ToString ()
{
return String.Join ("Employee: ", this.Employees.Select (e => e.Fullname).ToArray<string>());
}
答案 1 :(得分:1)
您可以尝试覆盖ToString
,如下所示:
public override string ToString()
{
return string.Join(",", this.Employees
.Select(employee => $"Employee: {employee.FullName}"));
}
答案 2 :(得分:1)
如果我正确理解您的要求,以下带有覆盖.ToString()的类将解决您的问题。在这里,我使用了两个类,一个是Employee详细信息,另一个是第一个类的列表
public class Employee
{
public int EmpCode { get; set; }
public string FullName { get; set; }
public override string ToString()
{
return String.Format("Employee Code : {0} \n Employee Full Name : {1}", this.EmpCode, this.FullName);
}
}
public class EmployList
{
public List<Employee> EmployeeList = new List<Employee>();
public override string ToString()
{
StringBuilder strBuilder = new StringBuilder();
foreach (var item in EmployeeList)
{
strBuilder.AppendLine(item.ToString());
}
return strBuilder.ToString();
}
}
如何使用上述课程
EmployList listObject = new EmployList();
listObject.EmployeeList.Add(new Employee(){EmpCode=1,FullName="suji"});
listObject.EmployeeList.Add(new Employee(){EmpCode=11,FullName="jon"});
listObject.EmployeeList.Add(new Employee(){EmpCode=12,FullName="anu"});
listObject.EmployeeList.Add(new Employee(){EmpCode=13,FullName="achu"});
Console.WriteLine(listObject.ToString());