格式化字符串-编译时检查

ram*_*ram 2 .net c# string string.format

有什么方法可以在编译时检查格式字符串吗?

例子:

Console.WriteLine("{0} is a really {1} site", "stackoverflow.com", "cool");//this will run
Run Code Online (Sandbox Code Playgroud)

//这将给出一个异常,因为只提供了一个参数

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."
Run Code Online (Sandbox Code Playgroud)

如果格式字符串的格式不正确(即此处 1 之后缺少“}”)

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

Exception: Input string was not in a correct format.
Run Code Online (Sandbox Code Playgroud)

Ed *_*fer 5

不,您不能在此处添加编译时验证。这是资源字符串和格式化字符串的缺点之一。您可以采取一些措施来缓解您的问题。

  1. 对您的公共接口进行彻底的单元测试,以确保您的字符串格式正确。
  2. 使用ReSharper等工具可以执行静态分析,并让您在运行应用程序之前了解这些问题。
  3. 事情是更好的三分之二。