roo*_*roo 6 .net c# compiler-construction string
在我的代码中,有几个字符串用作访问资源的密钥.这些密钥具有特定格式,例如
string key = "ABC123";
Run Code Online (Sandbox Code Playgroud)
目前,所有这些键都存储为字符串,但我想使事情更健壮和类型安全.理想情况下,我想在编译时检查字符串是否格式正确.
下一步是创建一个从字符串初始化的ResourceKey类.然后,我可以在运行时检查字符串的格式,例如
ResourceKey key = "ABC123";
Run Code Online (Sandbox Code Playgroud)
其中ResourceKey定义为:
using System.Diagnostics;
using System.Text.RegularExpressions;
class ResourceKey
{
public string Key { get; set; }
public static implicit operator ResourceKey (string s)
{
Debug.Assert(Regex.IsMatch(s, @"^[A-Z]{3}[0-9]{3}$"));
return new ResourceKey () { Key = s };
}
}
Run Code Online (Sandbox Code Playgroud)
我真正想做的是拥有一种编译时断言,以便在任何人试图使用无效密钥时程序无法构建.例如
ResourceKey k1 = "ABC123"; // compiles
ResourceKey k2 = "DEF456"; // compiles
ResourceKey k3 = "hello world"; // error at compile time
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这个目标?
谢谢
您可以使用单元测试来检查值.我的一个同事必须在一个项目中做类似的事情,我们需要确保某个命名空间中的所有类都应用了某些属性.
使用您的构建运行单元测试(无论如何你都这样做?:)或作为集成构建的一部分.这将使您的源更清洁,并且您不必引入执行断言的代码.