从C#构造函数中删除多余的逗号
本文关键字:多余 删除 构造函数 | 更新日期: 2023-09-27 18:25:06
以下是我所得到的,我需要防止控制台在主程序上返回额外的逗号,所以我可能需要重写字符串e。Month、description等应该仍然有逗号,但如果没有"note"之类的内容,这些额外的逗号就会消失。
public override string ToString()
{
string e = description + ", " + month + day + year + ", " + amount.ToString("C") + ", ";
e = e + paymentMethod + ", " + trip + ", " + note;
return e;
}
你可以尝试这样的方法,过滤掉空元素:
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#:
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());
}
你可以这样重写ToString
,这是你想要的吗?
public override string ToString()
{
string e = description + " " + month + day + year + " " +
amount.ToString("C") + " ";
e = e + paymentMethod + " " + trip + " " + note;
return e;
}