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?

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

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.