0

我使用一个字符串进行如下查询:

Dim auxstring as String
auxstring = String.Format("val1 = {0}, val2 = {1}, valn ={n}", control1.Value,   control2.Value, controln.Value)

我想要做的是将 String.Format 转换为更具可读性的东西,如下所示:

<object like an array>.<value1> = data1
<object like an array>.<value2> = data2
<object like an array>.<valuen> = datan

<other object like an array>.<value1> = control1.property
<other object like an array>.<value2> = control1.property
<other object like an array>.<valuen> = control1.property

auxstring = String.Format(<object like an array with values>, <object like an array with controls.properties>)

为了可读性:)

4

3 回答 3

0

这是解决此问题的一种快速方法,您是否将其视为对现有代码的改进是一个见仁见智的问题。

List<string> vals = new List<string>();
int[] data = new int[] { 1, 2, 3, 4 };

for (int i = 0; i < data.Length; i++)
{
    vals.Add(string.Format("val{0} = {1}", i + 1, data[i]));
}

string auxstring = string.Join(",", vals.ToArray());

这个简单的示例使用一个整数数组,但是将其更改为任何类型并访问索引项(在循环中)而不是索引值本身的属性是微不足道的。

于 2013-06-27T17:27:37.120 回答
0

我想要做的是将 String.Format 转换为更具可读性的东西

使用行扩展符号(_):

    auxstring = String.Format("val1 = {0}, val2 = {1}, valn ={n}", _
                              control1.Value, _
                              control2.Value, _
                              controln.Value)

请记住,它前面需要一个空格,并且必须到该行的最后一个字符。

如果你想要更简洁的东西,我建议重载格式函数。这样你就可以让 Option Strict On 并且不必担心后期绑定的问题。

 Dim Values() As Integer = {0, 1, 2}

 Dim ValueString As String = Format("val", Values)  

 Public Function Format(Of T)(Identifier As String, ObjectArray() As T) As String
     Format = ""
     For I = 0 To ObjectArray.Length - 1
         Format += String.Format(Identifier + I.ToString + " = {0} , ", ObjectArray(I).ToString)
     Next
     Format = Format.TrimEnd({" "c, ","c})
 End Function

ValueString 看起来像这样,"val0 = 0 , val1 = 1 , val2 = 2" 这将接受任何带有 ToString 方法的数组对象。

于 2013-06-27T17:47:05.197 回答
0

您可以创建属性列表,然后动态生成格式字符串以匹配属性数量:

    Dim properties = {
        control1.property,
        control2.property,
        control3.property}

    Dim formatString = String.Join(", ", properties.Select(Function(_trash, i) String.Format("val{0} = {{{0}}}", i)))

    Dim auxstring = String.Format(formatString, properties)
于 2013-06-27T17:59:47.403 回答