假设下面...评估和演示串码(插值)
Dim x as string = "hello"
dim y as string = "world"
dim z as string = "{x} {y}" 'Note: no $ (not interpolation)
我想调用一个方法是通过z。如果将返回的“hello world”
注:30z可有0或更多{},并应根据调用者的范围进行评估
这可能吗?
假设下面...评估和演示串码(插值)
Dim x as string = "hello"
dim y as string = "world"
dim z as string = "{x} {y}" 'Note: no $ (not interpolation)
我想调用一个方法是通过z。如果将返回的“hello world”
注:30z可有0或更多{},并应根据调用者的范围进行评估
这可能吗?
串插在VB.NET 14可为了内插一个字符串,请执行下列操作...
Dim x as string = "hello"
Dim y as string = "world"
Dim z = $"{x} {y}"
这是简写......
dim z = String.Format({0}{1}, x,y)
欲了解更多信息VB.NET 14,请参阅14 Top Improvements in Visual Basic 14
如果在占位符中使用数字而不是字母,则使用String.Format
:
Dim x As String = "hello"
Dim y As String = "world"
Dim z As String = "{0} {1}"
Dim output As String = String.Format(z, x, y)
由于任何字符串可以传递给String.Format
作为格式字符串,即使它是动态的,因为其余的参数是一个参数数组,你甚至可以做这样的事情(尽管它是围绕着不必要的包装已经使用的方法):
Public Function MyFormat(format As String, values() As Object) As String
Return String.Format(format, values)
End Function
喜欢的东西SmartFormat.NET,与named placeholders可能是你在找什么。您需要传递所有可能的上下文变量 - 我不知道有什么方法来捕获当前范围。
Dim x As String = "hello"
Dim y As String = "world"
Dim notUsed As String = "Don't care"
Dim z As String = "{x} {y}"
Dim output As String = Smart.Format(z, New With { x, y, notUsed })
Console.WriteLine(output)
hello world
的问题是,在Z字符串值是不是在设计时已知和{}的数量也是不知道的,所以我在寻找一种方法在运行时,以评估这一点。 – George
@George I更新了我的答案,证明它即使在动态值下也能正常工作。 –