In projects, ing and conversion of domain enumeration and DTO enumeration are sometimes used. There is a real problem: if the field enumeration items change, and the DTO enumeration items are not updated in time, this will cause ing failure. So how can we avoid such problems?
First, check whether the ing between domain enumeration and DTO enumeration is complete.
class Program { static void Main(string[] args) { var queryOrderStatus = (QueryOrderStatus)OrderState.Active; Console.WriteLine(queryOrderStatus); Console.ReadKey(); } } public enum OrderState { NotActivated, Active, RequiresReActivation } public enum QueryOrderStatus { NotActivated, Active, RequiresReActivation }
Output result: Active
Suppose we add an enumeration item to the domain model.
public enum OrderState { NotActivated, Active, RequiresReActivation, Locked }
On the client.
class Program { static void Main(string[] args) { var queryOrderStatus = (QueryOrderStatus)OrderState.Locked; Console.WriteLine(queryOrderStatus); Console.ReadKey(); } }
Output result: 3
If you change the client to the following:
class Program { static void Main(string[] args) { var queryOrderState = (QueryOrderStatus)OrderState.Locked; if(queryOrderState == QueryOrderStatus.Active) Console.WriteLine("Active"); if(queryOrderState == QueryOrderStatus.NotActivated) Console.WriteLine("NotActivated"); if(queryOrderState == QueryOrderStatus.RequiresReActivation) Console.WriteLine("RequiresReActivation"); Console.ReadKey(); } }
Output result: Nothing
That is to say, when the domain enumeration changes, the DTO enumeration is not updated in due time, which may cause ing failure. How can we avoid it?
-- Use enum. tryparse () to implement secure conversion of enumeration
Use enum. tryparse () to change the client:
Class program {static void main (string [] ARGs) {var domainstate = orderstate. Locked; queryorderstatus querystate; If (! Enum. tryparse (domainstate. tostring (), Out querystate) {Throw new formatexception ("enumeration item '" + domainstate + "' does not exist in the corresponding DTO");} console. readkey ();}}
Running error:
This is the preset error reporting method.