作为一个爱好项目的思想实验,我一直在想一种方法来确保这种微妙的错误/错别字不会发生:
public void MyMethod(int useCaseId)
{
// Do something with the useCaseId
}
public void SomeOtherMethod()
{
int userId = 12;
int useCaseId = 15;
MyMethod(userId); // Ooops! Used the wrong value!
}
这个错误很难找到,因为没有编译时错误,你甚至不一定会在运行时遇到异常。你只会得到“意想不到的结果”。
为了以简单的方式解决这个问题,我尝试使用空枚举定义。有效地使用户 id 成为数据类型(而不是类或结构):
public enum UseCaseId { // Empty… }
public enum UserId { // Empty… }
public void MyMethod(UseCaseId useCaseId)
{
// Do something with the useCaseId
}
public void SomeOtherMethod()
{
UserId userId = (UserId)12;
UseCaseId useCaseId = (UseCaseId)15;
MyMethod(userId); // Compile error!!
}
你怎么看?