Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我目前正在研究一个系统,并且作为接口的一部分提供的方法之一接收一个国家的状态作为字符串 -
public DoStuff(string state) { //do stuff }
状态只能是一系列先前已知值中的一个。我知道用枚举参数替换字符串参数会更好,但由于我无法控制的某些因素,接口需要保持原样。
我的问题是:通常最好尽快将字符串映射到枚举(如果可以的话)并从那时起使用枚举类型而不是字符串?还是将其保留为字符串,并且每当某些内容依赖于状态的值时,使用 switch 语句是否更好?
我更愿意尽可能快地使用枚举。它在开发中节省了很多错误,并确保代码更干净,更容易理解。
枚举还可以作为您期望的不同状态的明确定义。
If it is a fixed and known set of data then go for Enum as soon as possible. This is a good design practice and very easy for your team to understand.