string.Format
定义的详尽列表为
public static String Format(IFormatProvider provider,String format, params object[] args);
public static String Format(String format, params object[] args);
public static String Format(String format, object arg0, object arg1, object arg2);
public static String Format(String format, object arg0);
public static String Format(String format, object arg0, object arg1);
和以下代码
using System;
public class Program
{
public static void Main()
{
var myFormat = "(0:'{0}';1:'{1}')";
var myParams = new object[] {"arg1", "arg2"};
var myString = MyTest(myFormat, myParams);
Console.WriteLine(myString);
}
public static string MyTest(string format, params object[] args)
{
string myFirstArg = "arg0";
var result = string.Format(format, myFirstArg, args);
return result;
}
}
会给予
(0:'arg0';1:'System.Object[]')
现在的问题是如何将arg0
中的myParams
包括进来,以便输出
(0:'arg0';1:'arg1';2:'arg2')
PS。 (假设myFormat = "(0:'{0}';1:'{1}';2:'{2}')";
)
答案 0 :(得分:2)
您可以使用LINQ:
public static string MyTest(string format, params object[] args)
{
string myFirstArg = "arg0";
var result = String.Format(format, (new[] { myFirstArg }).Union(args).ToArray());
return result;
}
答案 1 :(得分:1)
您必须创建一个以arg0作为第一个元素的数组。试试这个:
using System.Linq;
public static string MyTest(string format, params object[] args) {
var newarr = new object[] { "arg0" };
newarr.Concat(args);
var result = string.Format(format, newarr);
return result;
}
答案 2 :(得分:0)
我将 Prepend 扩展方法用于此类任务:
class Program
{
static void Main()
{
string myFirstArg = "arg0";
var format = "(0:'{0}';1:'{1}';2:'{2}')";
var args = new object[] { "arg1", "arg2" };
var result = string.Format(format, args.Prepend(myFirstArg).ToArray());
}
}
public static class IEnumerableExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> collection, T element)
{
yield return element;
foreach (var e in collection) yield return e;
}
}