A few days ago, when I write a value that is automatically read from XML and injected into object attributes, I do not want to write the original data of the int type or the string type for convenience, but when read from XML, it is of the string type. In this case, the string type is automatically converted to the object property type.
For example, string => int/long/double/DateTime/enum/String/bool ....
At the beginning, it was a bit silly to come up with a long switch.
But suddenly, when asp.net mvc was used, didn't they automatically convert the values in the form or URL to the corresponding type?
Just look at how people do it.
Use the decompilation software Reflector to open System. Web. Mvc (right-click VS2008 and choose Reflector to open it. The default location is C: Program FilesMicrosoft ASP. NETASP. net mvc 1.0AssembliesSystem.Web.Mvc.dll)
All the way down the access path of asp.net mvc. I found that there was another simple method. I listed my simple DEMO here. I believe it is easy for everyone to understand:
Using System;
Using System. ComponentModel;
Namespace YcoeXu. Common
{
Public static class StringExtensions
{
/// <Summary>
/// Format the string to the specified data type
/// </Summary>
/// <Param name = "str"> </param>
/// <Param name = "type"> </param>
/// <Returns> </returns>
Public static Object Format (this String str, Type type)
{
If (String. IsNullOrEmpty (str ))
Return null;
If (type = null)
Return str;
If (type. IsArray)
{
Type elementType = type. GetElementType ();
String [] strs = str. Split (new char [] {;});
Array array = Array. CreateInstance (elementType, strs. Length );
For (int I = 0, c = strs. Length; I <c; ++ I)
{
Array. SetValue (ConvertSimpleType (strs [I], elementType), I );
}
Return array;
}
Return ConvertSimpleType (str, type );
}
Private static object ConvertSimpleType (object value, Type destinationType)
{
& N