有没有办法在编译时检查格式字符串?
例子:
Console.WriteLine("{0} is a really {1} site", "stackoverflow.com", "cool");//this will run
//这将给出一个异常,因为只提供了一个参数
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."
如果格式字符串的格式不正确(即此处 1 后缺少“}”)
Console.WriteLine("{0} is a really {1 site", "stackoverflow.com","cool");
Exception: Input string was not in a correct format.
最佳答案
不,你不能在这里添加编译时验证。这是资源字符串和格式字符串的缺点之一。您可以采取一些措施来缓解您的问题。
- 对您的公共(public)接口(interface)进行彻底的单元测试,以确保您的字符串格式正确。
- 使用类似 ReSharper 的工具可以执行静态分析并让您在运行应用程序之前了解这些问题。
- 事情是更好的三分。
关于c# - 格式化字符串-编译时检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2029003/