2016-01-25 115 views
-1

我想使用string.Format來格式化一個string,但它會拋出一個異常。C#string.Format拋出異常

var format = "public {0} {1} { get; {2}set; }"; 
     var arg0 = "long"; 
     var arg1 = "Ticks"; 

     var formatedString = string.Format(format, arg0, arg1, null); 

最後一行拋出具有以下細節System.FormatException

System.FormatException was unhandled 
    HResult=-2146233033 
    Message=Input string was not in a correct format. 
    Source=mscorlib 
    StackTrace: 
     at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) 
     at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args) 
     at System.String.Format(String format, Object arg0, Object arg1, Object arg2) 
     at ConsoleApplication1.Program.Main(String[] args) in E:\lab\cheque\helloworldprism\ConsoleApplication1\ConsoleApplication1\Program.cs:line 11 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

回答

4

它不喜歡的{並在}{ get; {2}set; }你必須使用他們兩個

逃避花括號
var format = "public {0} {1} {{ get; {2}set; }}"; 
3

你需要跳過你的花括號,使用另一個花括號將逃脫它。

var format = "public {0} {1} {{ get; {2}set; }}";