Example #1
0
        /// <summary>
        ///
        /// <seealso cref="TypeExtensions.GetArrayElementType(System.Type)"></seealso>
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="arrayType"></param>
        /// <returns>List&lft;arrayType.GetArrayElementType() or object&rht;</returns>
        object ReadArray(TextReader stream, System.Type arrayType)
        {
            Assert.IsTrue(arrayType.IsArrayOrList(), $"arrayType({arrayType.FullName}) is not Array Type...");

            Assert.IsTrue(stream.IsMatchPeek('['));
            stream.Read();
            Assert.IsTrue(stream.SkipTo(SPACE_CHARS));

            var elementType   = arrayType.GetArrayElementType();
            var refCache      = GetListTypeCache(elementType);
            var addMethodInfo = refCache.GetCachedMethodInfo("Add");

            var tmpList = refCache.CreateInstanceWithCache("ctor", null);

            while (!stream.IsMatchPeek(']'))
            {
                var value = ReadValue(stream, elementType);
                addMethodInfo.Invoke(tmpList, new object[] { value });

                Assert.IsTrue(stream.SkipTo(SPACE_CHARS));
                if (SkipNextCamma(stream))
                {
                    Assert.IsTrue(stream.SkipTo(SPACE_CHARS));
                }
            }
            stream.Read(); // skip ']' if not end of string

            //instanceをarrayTypeへキャストする
            if (arrayType.IsArray)
            {
                var count     = (tmpList as IList).Count;
                var arrayCtor = arrayType.GetConstructor(new System.Type[] { typeof(int) });
                var arrayInst = arrayCtor.Invoke(new object[] { count });

                var toArrayMethod = refCache.GetCachedMethodInfo("ToArray");
                var srcArray      = (System.Array)toArrayMethod.Invoke(tmpList, new object[] { });
                System.Array.Copy(srcArray, (System.Array)arrayInst, count);
                return(arrayInst);
            }
            else
            {
                //List<>の時
                return(tmpList);
            }
        }