zoukankan      html  css  js  c++  java
  • 将字符串转化为某种类型

       //将字符串转化为type型.
        private object parse(string s, Type t)
        {
            //如果字符串是一个string,直接返回.
            if (t.IsAssignableFrom(typeof(string))) return s;
            //如果字符串是一个数组,那么将其解析为数组并返回.
            if (t.IsArray) return parseArray(s, t);

            //构造并调用tpe的Parse方法.
            BindingFlags flags = BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.Public;
            MethodInfo parseMethod = t.GetMethod("Parse", flags, nullnew Type[] { typeof(string) }, null);
            if (parseMethod != null && parseMethod.ReturnType == t)
            {
                return parseMethod.Invoke(nullnew object[] { s });
            }
            else
            {
                throw new ApplicationException("Can't parse " + t.FullName + " because it doesn't have a static Parse() method");
            }
        }

        //将字符串转化为某种类型的数组.
        private object[] parseArray(string s, Type arrayType)
        {
            string[] strings = s.Split(new char[] { ',' });
            object[] result = new object[strings.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                result[i] = parse(strings[i], arrayType.GetElementType());
            }
            return result;
        }

  • 相关阅读:
    字串变换
    单词接龙
    二叉搜索树
    搜索专题(未完)
    单调栈
    单调队列练习(切蛋糕&好消息,坏消息)
    队列专题
    滑动窗口/【模板】单调队列
    Linux下如何查看硬件信息?
    Git 居然可以用来跟女神聊天?
  • 原文地址:https://www.cnblogs.com/robyn/p/3729321.html
Copyright © 2011-2022 走看看