zoukankan      html  css  js  c++  java
  • String转成任意基本类型

    尝试别的方法,一直找不到好的。

            /// <summary>
            
    /// 转成基本的类型(支持可空类型)
            
    /// </summary>
            public static T Convert<T>(this string str, T defaultValue)
            {
                
    if (String.IsNullOrEmpty(str))
                    
    return defaultValue;

                var type 
    = typeof(T);


                var typeName 
    = type.FullName;

                
    if (type.Name == "Nullable`1")
                {
                    var m 
    = Regex.Match(typeName, @"((?<=\[)(\w+.\w+)(?=,))");

                    type 
    = Type.GetType(m.Value);
                }


                MethodInfo method 
    = null;
                
    foreach (var m in type.GetMethods())
                {
                    
    if (m.Name == "Parse" && m.GetParameters().Length == 1)
                    {
                        method 
    = m;
                        
    break;
                    }
                }

                var result 
    = defaultValue;
                
    try
                {
                    
    if (method != null)
                        result 
    = (T)method.Invoke(nullnew[] { str });
                }
                
    catch
                {
                    
    return defaultValue;
                }

                
    return result;
            }
  • 相关阅读:
    mac zsh选择到行首的快捷键
    phalcon下拉列表
    tinycore remaster方法
    bundle安装方法
    centos7安装avahi
    pydoc介绍
    macosx下apache的默认用户为daemon
    centos配置ssh免密码登录后,仍提示输入密码
    xampp默认项目文件夹htdocs
    微信开发:"errcode": -1000,"errmsg": "system error"错误的解决办法
  • 原文地址:https://www.cnblogs.com/mad/p/1625342.html
Copyright © 2011-2022 走看看