2017-05-18 35 views
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或更多{},并应根据调用者的范围进行评估

这可能吗?

回答

1

串插在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

0

如果在占位符中使用数字而不是字母,则使用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 
+0

的问题是,在Z字符串值是不是在设计时已知和{}的数量也是不知道的,所以我在寻找一种方法在运行时,以评估这一点。 – George

+0

@George I更新了我的答案,证明它即使在动态值下也能正常工作。 –

0

喜欢的东西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 
+0

与此相关的问题是在设计时我不知道{}有多少个变量名称。我所知道的是z和z可以在运行时改变。 – George

+0

@George你需要传入_all possible_变量,你应该在设计时知道这些变量。我不知道任何可以传入当前范围的方式,包括局部变量,虽然“Smart.Format”的参数可能是“Me”,它可以让你引用任何在类级定义的公共变量。 – Mark