gpt4 book ai didi

c# - 字符串插值中需要一个常量值

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:55 36 4
gpt4 key购买 nike

我的代码如下

static string Foo(string str, int width)
{
return $"{str,width}";
}

编译器不允许我使用 width 变量。我怎样才能把它传递给一个方法?

最佳答案

在这种情况下,使用 string.Format 可能比插值更好。

var str = "test";
var width = 10;
var fmt = $"{{0,{width}}}";
var result = string.Format(fmt, str);

但是如果你只是用空格填充 PadLeftPadRight 会更干净......

return str.PadLeft(width, ' ');

关于c# - 字符串插值中需要一个常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615735/

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