程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 如何將String類型轉換成任意基本類型

如何將String類型轉換成任意基本類型

編輯:C#入門知識

前幾天,在寫一個自動從XML中讀取數值並注入到對象屬性中去的時候,為了方便,不想把原來是int類型的寫與string類型,但是從XML裡讀取出來的時候,都是string類型。這時就需要將string類型自動地根據對象屬性的類型轉換過來。

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

剛開始的時候,確實有點犯傻,來個長長的switch。

但是突然間想到,在使用asp.net mvc的時候,它們不是也把從表單或URL中傳上來的值自動轉換成對應的類型了嗎?

眼前一亮,就這麼整,看看人家怎麼做到的。

使用反編譯軟件Reflector打開System.Web.Mvc(直接在VS2008下右鍵選擇Reflector打開就行了,默認位置在C:Program FilesMicrosoft ASP.NETASP.NET MVC 1.0AssembliesSystem.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)
        {
          &n

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved