For the data type conversion class, I think 99% of the people in the blog have written it, no matter what you useProgramming LanguageAll should involve data type conversion. Here I will talk about some of my ideas. If you think it is appropriate, you can adopt it. If you think it is not appropriate, you can move over and take a little lighter.
The data type conversion mentioned in this article mainly refers. NET provides conversions between simple data types, such as object, String, bool, datetime, Int, long, and double.
1. Forced conversion (XXX) OBJ, where obj is the object for data conversion, and XXX is the target data type for data conversion.
Advantage: When obj is of the XXX type, I think the conversion performance and efficiency are still very high.
Disadvantage: When obj is not of the XXX type, an exception will be thrown. If any conversion fails, we will not go into detail here.
2. Try {... convert. toxxx (OBJ)...} catch {...} method;
Advantage: You can convert the data into the target data as much as possible, and handle exceptions that cannot be converted.
Disadvantage: throwing an exception still causes some performance impact.
3. Convert the data into a string, verify the data type by using a regular expression, and then convert the data.
Advantage: compared with the second method, the exception throws can be reduced to a certain extent;
Disadvantage: It is troublesome to write some regular expressions. In addition, the obj. tostring () operation is performed before data conversion.
4. XXX. tryparse (OBJ, out XXX outvalue)
Advantage: This method uses the built-in method of. Net to determine whether the data can be converted to the target type. In asynchronous operations, it can also guide whether the conversion is successful and obtain the value after the conversion is successful.
Disadvantage: The OBJ. tostring () method is also required before data conversion.
The following describes a set of data conversion methods I have used. Here is only an example, from the object type to the int type:
/// <Summary>
/// Convert an object to an int
/// </Summary>
/// <Param name = "OBJ"> Object To be converted </Param>
/// <Param name = "defaultvalue"> Default Value returned when conversion fails </Param>
/// <Returns> </returns>
Public Static Int Toint ( Object OBJ, Int Defaultvalue)
{
If (OBJ = Null | OBJ = dbnull. value)
{
Return Defaultvalue;
}
If (OBJ Is Int )
{
Return ( Int ) OBJ;
}
Int RET;
If (! Int . Tryparse (obj. tostring (), Out RET ))
{
Loghelper. writelog ( " Write down the log information of data conversion failure here... " );
Return Defaultvalue;
}
Return RET;
}
I personally think this method has done a good job in the handling of conversion errors!
ASP. NET development technology exchange group:67511751(Recruitment ...)