是否可以将插值字符串作为参数传递给方法? [英] Is it possible to pass interpolated strings as parameter to a method?
问题描述
我已经开始使用插值字符串(新的C#功能6),它是非常有用和优雅。但根据我的需要我必须要通过字符串格式作为参数的方法。喜欢的东西下一:
I have started to use Interpolated Strings (new feature of C# 6) and it is really useful and gracefully. But according to my needs I have to pass format of string to a method as a parameter. Something like next:
MyMethod(string format)
在过去,我用它在未来的方式:
In the past, I used it in the next way:
MyMethod("AAA{0:00}")
现在我想这个代码:
MyMethod($"AAA{i:00}")
但是,这并不工作,因为 I
方法内创建,并超出范围在这种情况下。
But this doesn't work, because i
is created inside of the method and is out of scope in this context.
是否有可能使用任何伎俩通过插值字符串作为参数的方法?
Is it possible to use any trick for passing interpolated strings as a parameter to a method?
推荐答案
您不能这样做,这不会是一个很好的主意 - 这意味着你使用的是局部变量从另一个方法结果
这会破坏这一功能的目的 - 有编译器可核实的字符串插值和有约束力的局部变量。
You cannot do that, and that would not be a very good idea either - it means you are using local variables from another method.
This would defeat the purpose of this feature - to have compiler verifiable string interpolation and binding to local variables.
C#有几个很好的替代品。例如,使用一个函数功能
:
C# has several good alternatives. For example, using a Func
:
public void MyMethod(Func<int,string> formatNumber)
{
int i = 3;
var formatted = formatNumber(i);
}
使用为:
MyMethod(number => $"AAA{number:00}");
这是比你有什么今天更好 - 那就是你有格式化字符串(?S)和其。使用在不同的地方
This is better than what you have today - where you have the format string(s?) and its usage in different places.
如果你有超过一个变量这种方法可以扩展,但认为它们组合到一个类(或结构)更多 - 对 FUNC
看起来好多了,你的代码将更具可读性。这个类也可以覆盖的ToString()
,这可能是对你有用。
If you have more than a single variable this approach can scale, but consider grouping them into a class (or a struct) - the func
will look much better, and your code will be more readable. This class can also override .ToString()
, which might be useful for you.
另一个简单的办法是通过只是格式为:的MyMethod(00)
和 i.ToString(格式)
,但是,只有在工作您大概简单的例子。
Another simple option is to pass just the format: MyMethod("00")
and i.ToString(format)
, but that only works in your presumably simplified example.
这篇关于是否可以将插值字符串作为参数传递给方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!