简体   繁体   English

C#string.Format引发异常

[英]C# string.Format throws exception

I am trying to format a string using string.Format but it throws an exception. 我正在尝试使用string.Format格式化string但是会引发异常。

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

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

The last line throws a System.FormatException with the following details: 最后一行抛出带有以下详细信息的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: 

It does not like the { and the } in the { get; {2}set; } 它不喜欢{ get; {2}set; }{} { get; {2}set; } { get; {2}set; } { get; {2}set; } you have to escape curly braces by using two of them { get; {2}set; }您必须使用其中两个来使花括号转义

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

您需要转义大括号,使用另一个大括号即可转义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM