C#类型转换,可以转换多个以英文逗号分隔的字符串为常用的基本类型或 Guid 类型...

代码可以胜过一切!

/*
=============================================================================
作者:Bruce Liu
博客地址:Http://music.cnblogs.com
QQ:403350327
谢谢您的支持,欢迎您的转载,转载时请注明,谢谢!
=============================================================================	
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;

namespace TempConApp
{
    /// <summary>
    /// 通用工具类
    /// </summary>
    public static class CommonUtility
    {
        /// <summary>
        /// 根据用英文逗号连接的字符串动态强制转换成对应类型的只读集合
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="source">需要转换对应类型的字符串,多个用逗号分隔</param>
        /// <returns>只读集合</returns>
        public static ReadOnlyCollection<T> ParseTypeBySplitWithComma<T>(string source) where T : struct
        {
            Type t = typeof(T);
            bool isBasicValueType = t == typeof(byte) || t == typeof(short) || t == typeof(int) || t == typeof(long) || t == typeof(float) || t == typeof(double) || t == typeof(DateTime) || t == typeof(decimal);
            bool isGuidValueType = t == typeof(Guid);
            if(!(isBasicValueType || isGuidValueType))
            {
                throw new ArgumentException("泛型参数错误!只能是 byte、short、int、long、float、double、DateTime、decimal 这些基本类型或 Guid 类型。");
            }
            string[] sourceItems = source.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            List<T> result = new List<T>();
            if (isBasicValueType)
            {
                MethodInfo methodInfo = t.GetMethod("Parse", new Type[] { typeof(string) });
                foreach (string item in sourceItems)
                {
                    //T objT = Activator.CreateInstance<T>();   //也可以实例化,把这个实例化后的对象 传到 Invoke 方法的第一个参数
                    result.Add((T)methodInfo.Invoke(null /* 这里要求 T 类型的实例,由于是 Stuct 类型,所以不需要实例化 */, new object[] { item }));
                }
            }
            else if (isGuidValueType)
            {
                ConstructorInfo constructorInfo = t.GetConstructor(new Type[] { typeof(string) });
                foreach (string item in sourceItems)
                {
                    result.Add((T)constructorInfo.Invoke(new object[] { item }));
                }
            }
            return result.AsReadOnly();
        }
    }
}
using System;
using System.Collections.ObjectModel;

namespace TempConApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //请注意:由于 decimal d = decimal.Parse("1,333"); 是正确的,还有 double、float 。所以,请您避免把 1333 写成 1,333
            string source = "bb40aefb-2085-4d0f-beb4-4b0ba5ec5511,f6dad8a5-4ff5-44b4-a968-0c7849064819,b6e599ca-3a2d-4bcf-9f80-8d57ad213648";
            ReadOnlyCollection<Guid> result = CommonUtility.ParseTypeBySplitWithComma<Guid>(source);
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

第二段 Demo 

using System;
using System.Collections.Generic;

namespace ConAppTestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> lt = ParseTypeBySplitWithComma("");
            foreach (var item in lt)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 根据用英文逗号连接的字符串,尝试着转换为整型的集合
        /// </summary>
        /// <param name="source">需要转换对应类型的字符串,多个用逗号分隔</param>
        /// <returns>集合</returns>
        public static List<int> ParseTypeBySplitWithComma(string source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            List<int> result = new List<int>();
            string[] sourceItems = source.Split(',');
            int itemValue;
            foreach (string item in sourceItems)
            {
                if (int.TryParse(item, out itemValue))
                {
                    result.Add(itemValue);
                }
            }
            return result;
        }
    }
}

谢谢您的浏览!

转载于:https://www.cnblogs.com/Music/archive/2011/02/23/c-sharp-convert-by-split.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值