[原创][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~~~

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

最新文章

  1. 闲来无聊,研究一下Web服务器 的源程序
  2. &lt;&lt; CocoaPods安装和使用教程 &gt;&gt;github code4app以及cocoachina 苹果官方文档
  3. 10个有关RESTful API良好设计的最佳实践
  4. WEB中的cookie
  5. Android调用Sqlite数据库时自动生成db-journal文件的原因
  6. MVC4 WebAPI(一)
  7. 收集一些常用的php正则表达式
  8. Excel 内容粘贴到DataGridView, DataGridView 粘贴到 Excel
  9. javascript正则表达式(二)——方法
  10. BZOJ 1257 余数之和sum(分块优化)
  11. css简单实现火焰效果
  12. .NET跨平台实践:再谈用C#开发Linux守护进程
  13. 3. leetcode 463 Island Perimeter
  14. E. Exposition
  15. 我推荐的 Java Web 学习路线
  16. Repository个人实践
  17. javascript 常见数组操作( 1、数组整体元素修改 2、 数组筛选 3、jquery 元素转数组 4、获取两个数组中相同部分或者不同部分 5、数组去重并倒序排序 6、数组排序 7、数组截取slice 8、数组插入、删除splice(需明确位置) 9、数组遍历 10、jQuery根据元素值删除数组元素的方)
  18. 使用PageHepler分页
  19. Servlet 使用ServletContext共享数据,读取web.xml配置
  20. 【转载】奇异值分解(SVD)计算过程示例

热门文章

  1. Linux下查看进程IO工具iopp
  2. 我的头上碧空晴朗——数据库存datetime问题
  3. javaScript [[scope]]学习笔记
  4. 【Henu ACM Round#15 B】A and B and Compilation Errors
  5. CCF模拟题 有趣的数
  6. 使用python创建cocos2d-x项目
  7. c++中六种构造函数的实现以及9中情况下,构造函数的调用过程
  8. 网站平台的favicon.ico的logo
  9. 搭建Disuz论坛社区
  10. JOISC 2018 Day 2 最差记者3