[C #] how to convert the string type to any basic type

Source: Internet
Author: User
Tags reflector

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?

Hoho ~~~

Just look at how people do it.

Use the decompilation software reflector to open the system. web. MVC (right-click vs2008 and choose reflector to open it. The default location is C:/program files/Microsoft ASP. net/asp. net MVC 1.0/assemblies/system. 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)
{
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)
{
Object returnvalue;
If (value = NULL) | destinationtype. isinstanceoftype (value ))
{
Return value;
}
String STR = value as string;
If (STR! = NULL) & (Str. Length = 0 ))
{
Return NULL;
}
Typeconverter converter = typedescriptor. getconverter (destinationtype );
Bool flag = converter. canconvertfrom (value. GetType ());
If (! Flag)
{
Converter = typedescriptor. getconverter (value. GetType ());
}
If (! Flag &&! Converter. canconverconverter (destinationtype ))
{
Throw new invalidoperationexception ("cannot be converted to type:" + value. tostring () + "=>" + destinationtype );
}
Try
{
Returnvalue = flag? Converter. convertfrom (null, null, value): converter. converconverter (null, null, value, destinationtype );
}
Catch (exception E)
{
Throw new invalidoperationexception ("type conversion error:" + value. tostring () + "=>" + destinationtype, e );
}
Return returnvalue;
}
}
}

 

DEMO:

Custom configuration in the configuration file:

1. Add a node to the <configsections> </configsections> node:

  <section name="XuConfig" type="System.Configuration.NameValueSectionHandler" />

2. Write configuration looks like this:

<Configsections>
//. Other code
<Section name = "xuconfig" type = "system. configuration. namevaluesectionhandler"/>
</Configsections>
<Xuconfig>
<Add key = "ID" value = "123"/>
<Add key = "name" value = "ycoexu"/>
<Add key = "Roles" value = "member, admin"/>
</Xuconfig>

Automatically load write classes

Using system;
Using system. reflection;
Using system. Collections. Specialized;
Using system. configuration;
Using ycoexu. Common;
Namespace ycoexu. Test
{
Public class xuconfig
{
Private xuconfig (){}
Private Static xuconfig Config = NULL;
Private Static xuconfig instance
{
Get
{
If (Config = NULL)
{
Config = new xuconfig ();
Type type = typeof (xuconfig );
// Read the xuconfig node from the configuration file
Namevaluecollection xuconfig = (namevaluecollection) configurationmanager. getsection ("xuconfig ");
// Match the corresponding Attribute Based on the key
Foreach (string key in xuconfig. allkeys)
{
Propertyinfo Pi = type. getproperty (key );
If (Pi = NULL | string. isnullorempty (xuconfig [Key])
Continue;
// Automatically convert the type and inject the value
Pi. setvalue (config, xuconfig [Key]. Format (PI. propertytype), null );
}
}
Return config;
}
}
Public int ID {set; get ;}
Public string name {set; get ;}
Public role [] roles {set; get ;}
Public void test ()
{
Console. writeline (xuconfig. instance. Name );
Console. writeline (xuconfig. instance. ID );
Foreach (role R in xuconfig. instance. Roles)
{
Console. writeline (R. tostring ());
}
}
}
Public Enum role
{
Guest,
Member,
Manager,
Admin
}
}

 

Note that you must add a reference: system. Configuration

Here we have made some extensions to the string so that it can be accessed directly as a string object method. Is it very convenient. Hoho ~~~

I learned a little bit about the project and found that no one has released this method on the Internet. I will write it here to share it with you, I believe it will be of great help for you to implement similar automatic conversion or assignment functions in the future.

Well, the company seems to be switching to PhP again. It just switched from Java to C # In the last year, and will switch to other languages next year. hoho ~~~

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.