gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:50:39 26 4
gpt4 key购买 nike

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

例子:

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.

最佳答案

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

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

关于c# - 格式化字符串-编译时检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2029003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com