首页 > 解决方案 > 优化将多个 int 变量输出为 String 的代码

问题描述

我声明了一些 int 变量:

[SerializeField] private int currentHP, currentMP, maxHP, maxMP, attack, intelligence, defense, speed, critChance;

我想将它们输出为“您的统计数据为 xx”的文本。我使用了以下代码并且它有效

if (maxHP > 0)
{
stats += string.Format("\n Your stat is {0}", maxHP);
}

但是,我想知道是否有办法避免为每个 int 复制粘贴此代码。可能吗?

谢谢!

标签: c#unity3doptimization

解决方案


首先,将每个统计数据放入一个数组中:

int[] statsArray = { currentHP, currentMP, maxHP, maxMP, attack, intelligence, defense, speed, critChance };

然后,使用LINQ 查询为每个统计信息创建一个字符串。请注意,您可以使用字符串插值

var strings = from stat in statsArray 
                where stat > 0 // filters out the non-positive stats, like your if statement does
                select $"\nYour stat is {stat}."; // string interpolation

然后,使用以下方法将字符串连接在一起string.Concat

stats = string.Concat(strings);

推荐阅读