开发者

format string- compile time checking

Is there any way to check the format string at compile time ?

Example:

Console.WriteLine("{0} is a really {1}开发者_JS百科 site", "stackoverflow.com", "cool");//this will run

//this will give an exception as only one argument is supplied

Console.WriteLine("{0} is a really {1} site", "stackoverflow.com");

Exception:"Index (zero based) must be greater than or equal to zero and less than the size of the argument list."

and if format string is not in the correct format (i.e. missing the "}" after 1 here )

Console.WriteLine("{0} is a really {1 site", "stackoverflow.com","cool");

Exception: Input string was not in a correct format.


No, you can't add compile-time verification here. This is one of the down-sides to resource strings and formatting strings. You can do a few things to mitigate your problem.

  1. Thoroughly unit test your public interfaces to be confident that your strings are being formatted correctly.
  2. Use tools like ReSharper that can perform static analysis and let you know about these problems before you run your application.
  3. Things are better threes.


While not really compile-time checking, ReSharper can warn you in Visual Studio when the number of arguments is wrong or the format string is in the wrong format.


No, there is no way to do this. Unit testing solves this problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜