gpt4 book ai didi

c# - 向 String.Join 添加新行?

转载 作者:行者123 更新时间:2023-11-30 13:56:20 24 4
gpt4 key购买 nike

所以我一直在疯狂地尝试在我的 String.Join 打印输出中添加一个新行,但似乎这是不可能的,或者我做错了什么?我都尝试过使用 "/n/r"Enivrorment.NewLine 以及创建一个类也创建一个新行

列表框我也想打印出来

ListBox1.Items.Add("Calories to lose 0.5kg per week: " +
string.Join(Environment.NewLine + "Calories to lose 1kg per week:",
bc.LoseOrGainWeightCalories(bc.MaintainWightCalories(), true)));

调用这个类:

public string[] LoseOrGainWeightCalories(double weight, bool lose) {
string[] array = new string[2];
double LoseGainWeight = this.weight;
if(lose==true) {
array[0] = Convert.ToString(LoseGainWeight - 500);
array[1] = Convert.ToString(LoseGainWeight - 1000);
} else {
array[0] = Convert.ToString(LoseGainWeight + 500);
array[1] = Convert.ToString(LoseGainWeight + 1000);
}
return array;
}

当前输出图片:

最佳答案

问题不在于 String.Join 方法:

$ csharp
csharp> string.Join(Environment.NewLine + "Calories to lose 1kg per week:",new double[] {13,21});
"13
Calories to lose 1kg per week:21"

因此,问题出在不呈现新行的 ListBox 上。您可以使用两种不同的解决方案来解决:

  1. 添加多个项目,如图所示here

因此您可以将每一行添加为一个新项目。这种方法的问题是用户可以选择一行,除非您愿意编写解决方案来防止这种情况发生。

因此您可以执行:

string s = "Calories to lose 0.5kg per week: " +
string.Join(Environment.NewLine + "Calories to lose 1kg per week:",
bc.LoseOrGainWeightCalories(bc.MaintainWightCalories(), true));
foreach (string si in Regex.Split(s,"\n"))
ListBox1.Items.Add(si);
  1. 编写一个渲染器,用多行写入一个元素,如所演示的 here .

(复制重要部分)

ListBox1.DrawMode = DrawMode.OwnerDrawVariable;
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e) {
int i = e.Index;
float heightLine = 10.0f;
string lines = listBox1.Items[i].ToString()Split(new string[] {Environment.NewLine},StringSplitOptions.None).Length;
e.ItemHeight = (int) Math.Ceil(heightLine*itemi);
}
private void listBox1_DrawItem (object sender, DrawItemEventArgs e) {
e.DrawBackground();
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
ListBox1.MeasureItem += listBox1_MeasureItem;
ListBox1.DrawItem += listBox1_DrawItem;

关于c# - 向 String.Join 添加新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com