这就是我所拥有的,我需要让控制台不要在主程序上返回额外的逗号,所以我可能需要重写字符串e。月份,描述等应该仍然有逗号,但如果没有“注释”之类的东西,那些额外的逗号就会消失。
public override string ToString()
{
string e = description + ", " + month + day + year + ", " + amount.ToString("C") + ", ";
e = e + paymentMethod + ", " + trip + ", " + note;
return e;
}
答案 0 :(得分:3)
您可以尝试这样的方法来过滤掉空元素:
public override string ToString()
{
string[] elements = new string[] { description,
String.Concat(month, day, year),
amount.ToString("C"), paymentMethod, trip, note };
return String.Join(", ", elements.Where(s => !String.IsNullOrWhiteSpace(s)));
}
更冗长的选项,但也更少混淆和C#2兼容:
private static void AddIfNotNull(List<string> elements, string value)
{
if (!String.IsNullOrEmpty(value))
elements.Add(value);
}
public override string ToString()
{
List<string> elements = new List<string>();
AddIfNotNull(elements, description);
elements.Add(String.Concat(month, day, year));
elements.Add(amount.ToString("C"));
AddIfNotNull(elements, paymentMethod);
AddIfNotNull(elements, trip);
AddIfNotNull(elements, note);
return String.Join(", ", elements.ToArray());
}
答案 1 :(得分:1)
您可以像这样重写ToString
,这是您想要的吗?
public override string ToString()
{
string e = description + " " + month + day + year + " " +
amount.ToString("C") + " ";
e = e + paymentMethod + " " + trip + " " + note;
return e;
}