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

标签 c# string-interpolation

我的代码如下

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/

相关文章:

postgresql - 事务中的游标在go和psql之间的行为不同

c# - 具有多个客户端的异步套接字服务器

c# - 如何从 LINQ 结果中删除,匹配数组中的元素

c# - 从命令提示符运行控制台应用程序而不启动新的控制台窗口

c# - 尝试将粗体应用于整行但不断获得空引用 - NPOI

python - 将字符串转换为 f 字符串

c# - 怎么改编码?

html - 在 Angular 4/Ionic 3 中通过文本插值渲染新行

scala - 字符串插值的符号名称

powershell - 使用扩展字符串作为 Powershell 函数参数