[原创][C#] 如何将String类型转换成任意基本类型

Posted on  2009-12-02 09:47  YCOE 阅读( 2843) 评论( 14)  编辑  收藏

前几天,在写一个自动从XML中读取数值并注入到对象属性中去的时候,为了方便,不想把原来是int类型的写与string类型,但是从XML里读取出来的时候,都是string类型。这时就需要将string类型自动地根据对象属性的类型转换过来。

比如string ==> int/long/double/DateTime/enum/String/bool....

刚开始的时候,确实有点犯傻,来个长长的switch。

但是突然间想到,在使用asp.net mvc的时候,它们不是也把从表单或URL中传上来的值自动转换成对应的类型了吗?

hoho~~~

眼前一亮,就这么整,看看人家怎么做到的。

使用反编译软件Reflector打开System.Web.Mvc(直接在VS2008下右键选择Reflector打开就行了,默认位置在C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 1.0\Assemblies\System.Web.Mvc.dll)

顺着asp.net mvc的访问路径,一路到了下来。发现原来还有一个这么简单的方法,这里直接把我简单的DEMO列出来,相信大家都很容易看明白了:


using  System;
using  System.ComponentModel; namespace  YcoeXu.Common
{
     public   static   class  StringExtensions
    {
         ///   <summary> 
         ///  将字符串格式化成指定的数据类型
         ///   </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)
        {
             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.CanConvertTo(destinationType))
            {
                 throw   new  InvalidOperationException( " 无法转换成类型: "   +  value.ToString()  +   " ==> "  +  destinationType);
            }
             try 
            {
                returnValue  =  flag  ?  converter.ConvertFrom( null ,  null , value) : converter.ConvertTo( null      ,  null , value, destinationType);
            }
             catch  (Exception e)
            {
                 throw   new  InvalidOperationException( " 类型转换出错: "   +  value.ToString()  +   " ==> "   + destinationType, e);
            }
             return  returnValue;
        }
    }
}

DEMO:

在配置文件里自定义配置:

1. 在<configSections></configSections>节点内添加节点:

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

2. 写配置看起来会是这样的:


     < configSections > 
      //..其它代码
       < 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 >

写个类自动加载


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);
                     // 从配置文件里读取XuConfig节点 
                    NameValueCollection xuConfig  =  (NameValueCollection)ConfigurationManager.GetSection( "XuConfig " );
                     // 根据Key匹配对应的属性 
                     foreach  (String key  in  xuConfig.AllKeys)
                    {
                        PropertyInfo pi  =  type.GetProperty(key);
                         if  (pi  ==   null   ||  String.IsNullOrEmpty(xuConfig[key]))
                             continue ;
                         // 自动转换类型并注入值 
                        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
    }
}

注意了,一定要添加一个引用:System.Configuration

这里对String进行了一些扩展,使它可以直接当成String对象的方法访问了,是不是很方便呢。hoho~~~

项目中的一点点心得,发现网上还没有人放出这种方法,这里就写出来给大家分享下,相信对大家以后进行类似的自动转换或赋值的功能实现会有很大的帮助

好啦,公司貌似又要转向PHP了,上年刚从java转到C#,明年又要转向其它语言了,hoho~~~

引用网友的一句话,做人要像柯南这么有霸气,走到哪里,人就死到哪里

如何将String类型转换成任意基本类型的更多相关文章

  1. Java String类型转换成Date日期类型

    插入数据库时,存入当前日期,需要格式转换 import java.text.SimpleDateFormat; formatter = new SimpleDateFormat( "yyyy ...

  2. C# 字符串string类型转换成DateTime类型 或者 string转换成DateTime?(字符串转换成可空日期类型)

    在c#中,string类型转换成DateTime类型是经常用到的,作为基本的知识,这里在此做个小结.一般来说可以使用多种方法进行转换,最常用的就是使用Convert.ToDateTime(string ...

  3. 字符串string类型转换成DateTime或DateTime?类型

    常用的Convert.ToDateTime方法 //将含有正确日期格式的string类型转换成DateTime类型 string strDate = "2014-08-01"; D ...

  4. C#String类型转换成Brush类型

    C#String类型转换成Brush类型: using System.Windows.Media; BrushConverter brushConverter = new BrushConverter ...

  5. 【转载】C#里怎么把string类型转换成double

    在C#的数字计算过程中,有很多的方法可以将字符串String类型的变量转换为double类型,double.Parse方法.Convert.ToDouble方法.double.TryParse方法等都 ...

  6. java中string类型转换成map

    背景:有时候string类型的数据取出来是个很标准的key.value形式,通过Gson的可以直接转成map 使用方式: Gson gson = new Gson(); Map<String, ...

  7. C#种将String类型转换成int型

    API: 有一点是需要注意的,那就是必须保证该String类型内全为数字,能确保转换正确: 1.int.Parse(str); 2.TryParse(str, out intA); 3. Conver ...

  8. android String 类型转换成UTF-8格式

    在android开发中,有时候会遇到汉字乱码的问题,在这个时候,吧String串加一个编码格式转换,转换成UTF-8的格式就可以了 public static String toUtf8(String ...

  9. Object类型转换成自定义类型(向下转型)

    Object类型转换成自定义类型 场景: 从数据库或者别的途径接收对象的时候用Object,但是用的时候怎么object点(方法提示 | alt+'/'),都点不出自定义类型的方法. 比如,数据库查询 ...

随机推荐

  1. How Chromium Displays Web Pages: Bottom-to-top overview of how WebKit is embedded in Chromium

    How Chromium Displays Web Pages This document describes how web pages are displayed in Chromium from ...

  2. VirtualBox内刚刚安装完CentOS6.9和7系统,无法调整屏幕的分辨率,也无法设置共享文件夹。解决的方法就是安装VirtualBox客户端增强包。

    VirtualBox内刚刚安装完CentOS6.9和7系统,无法调整屏幕的分辨率,也无法设置共享文件夹.解决的方法就是安装VirtualBox客户端增强包. 1.若直接安装客户端增强包会得到如下提示: ...

  3. 【Henu ACM Round#16 A】 Bear and Game

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 看看什么时候t[i]-t[i-1]>15. 输出t[i-1]+15就好. 不存在这样的i就输出min(t[n]+15,90) ...

  4. Nginx+tomcat+ssl免费证书配置

    0.说明 本文说描写叙述的方式是用nginx的443重定向到tomcat的8443,nginx的80port重定到tomcat的8080: 乱入:个人标记:caicongyang 1.nginx安装 ...

  5. 【Android实战】Android沉浸式状态栏实现(下)

    之前的Android沉浸式状态栏实现并没有考虑软键盘的影响,接下来的内容将会针对这个问题给出解决方式,先看一下效果图 这个是一个留言板的效果图: 即弹出软键盘的时候并不会导致整个布局上移. 详细怎样实 ...

  6. OL记载Arcgis Server切片

    概述: 本文讲述怎样在OpenLayers中调用Arcgis Server切片并显示. 思路: 在OpenLayers中载入Arcgis Server切片用XYZ图层,Arcgis Server的切片 ...

  7. ios in-house 公布整个过程(startssl认证)

    首先大体说一下步骤: 1.申请苹果enterprise 账号 为应用生成app id,provision profile等 详见:http://www.th7.cn/Program/IOS/20131 ...

  8. jquery15 on() trigger() : 事件操作的相关方法

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  9. vue ---- 组件传值之间使用 v-model

    父子组件通信,都是单项的,很多时候需要双向通信.方法如下: 1.父组件使用:msg.sync="aa"  子组件使用$emit('update:msg', 'msg改变后的值xxx ...

  10. 关于vuex的项目中数据流动方式

    vue的核心是数据驱动,所有数据变更的时机很重要,也就是watch的内容,一般是数据逻辑的操作.在使用vuex的项目中,我们在vuex中只是发请求.拿数据,在视图中来进行逻辑的操作.数据的更新. 1. ...