格式与字符串编译时检查 [英] format string- compile time checking

查看:134
本文介绍了格式与字符串编译时检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来检查格式字符串在编译时?

例如:

  Console.WriteLine({0}是一个真正的{1}网站,stackoverflow.com,酷); //这将运行
 

//这会给为只提供一个参数异常

  Console.WriteLine({0}是一个真正的{1}网站,stackoverflow.com);

异常:索引(基于零)必须大于或等于零且小于参数列表的大小。
 

如果格式字符串不正确的格式(即缺少}后1这里)

  Console.WriteLine({0}是一个真正的{1网站,stackoverflow.com,酷);

例外:输入字符串的不正确的格式。
 

解决方案

没有,你可以在这里添加编译时验证。这是向下双方资源字符串和格式字符串之一。你可以做一些事情,以减轻你的问题。

  1. 在彻底单元测试的公共接口,以确保您的字符串被格式正确无误。
  2. 使用如 ReSharper的工具,可以进行静态分析,让您了解这些问题,你运行你的应用程序之前。
  3. 东西还是三分球。

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

Example:

Console.WriteLine("{0} is a really {1} 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.

这篇关于格式与字符串编译时检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆