c# - 优化将多个 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 复制粘贴此代码。可能吗?
谢谢!
解决方案
首先,将每个统计数据放入一个数组中:
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);
推荐阅读
- node.js - 节点 MongoDB collection.findOne() 返回 null
- javascript - 如何将 emojioneArea(独立)选择值添加到文本字段?jQuery Rails 6.0.0
- c++ - GUI C++ - 绘制多行?(初学者问题)
- pytorch - 在 pytorch 中,Multi-gpus 不起作用,我该如何解决?
- python - 似乎我无法在两个或更多列上 parse_dates
- sql-server - INSERT 语句与 FOREIGN KEY 约束冲突?我试图在表''客户''中插入数据,但我总是得到这个错误
- javascript - AG Grid Angular 自定义工具提示不适用于两个组件
- python - 使用 Python 从 Cookie Jar 中提取特定的 Cookie
- python - 将pandas函数实现为numpy函数
- laravel - Laravel - 查询多个对象以过滤记录