string.Format(string, string)
需要2个字符串参数,以便您可以从数据库中把它们和它们直接套用:
string formatToApply = "{0} and some text and then the {1}";
string firstText = "Text";
string secondText = "finsh.";
// suppose that those strings are from db, not declared locally
var finalString = string.Format(formatToApply, firstText, secondText);
// finalString = "Text and some text and then the finish."
然而,说明符数量错误或参数错误数量很大。如果你有这样一个电话,它会抛出一个异常:
var finalString = string.Format(formatToApply, firstText);
//An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll;
//Additional information: Index (zero based) must be greater than or
//equal to zero and less than the size of the argument list.
所以包裹你的电话到try/catch/ (maybe) finally
相应地处理这种情况下您的需求。
后来编辑所需的例子之后被张贴:
第一个例子:你可能想利用DateTime类的从C#哪知道来格式化它的输出值。所以,你首先需要stringInput
转换成日期时间:
var inputDateTime = DateTime.Parse(stringInput);
var outputString = inputDateTime.ToString(inputFormat);
第二个例子:同样,你可能想利用Double类和转换的再次发生:
var inputDouble = Double.Parse(stringInput);
var outputString = inputDouble.ToString(inputFormat);
在这两个例子总结,您需要知道输入字符串的类型,您在注释中指定的类型(“日期的字符串表示形式”)。知道这一点,您可以利用每个特定的类以及格式化输出字符串的能力。否则,设计自己的某种通用格式化器将会很困难。一个简单的方法可能是这样的:
public string GetFormattedString(string inputString, string inputFormat, string type)
{
switch (type)
{
case "double":
var inputDouble = Double.Parse(inputString);
return inputDouble.ToString(inputFormat);
break;
case "datetime":
var inputDateTime = DateTime.Parse(inputString);
return inputDateTime.ToString(inputFormat);
break;
case "...": // other types which you need to support
default: throw new ArgumentException("Type not supported: " + type);
}
}
这switch
只是一个想法如何可能出现逻辑,但是你需要处理错误的Parse
方法和ToString
方法,如果你有很多类型的支持是更好地利用一些设计模式,如Factory
。
如果您添加值和格式的示例,问题会更加清晰 – ASh
给我们提供一些数据示例 – rbm
*“因为这些要求您现场声明您想要的格式和我的动态”*不是,他们需要字符串,它不需要内联定义,'string.Format(formatFromDb,valueFromDb)'应该工作得很好。 –