Exemplo n.º 1
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        /// <returns> </returns>
        protected override DataTable ChangeTypeImpl(ConvertContext context, object input, Type outputType,
                                                    out bool success)
        {
            success = true;
            var view = input as DataView;

            if (view != null)
            {
                return(view.ToTable());
            }
            var reader = input as IDataReader;

            if (reader != null)
            {
                if (reader.IsClosed)
                {
                    context.AddException("DataReader已经关闭");
                    success = false;
                    return(null);
                }
                var table1 = new DataTable();
                table1.Load(reader);
                return(table1);
            }

            var ee = (input as IEnumerable)?.GetEnumerator()
                     ?? input as IEnumerator
                     ?? (input as DataTable)?.Rows.GetEnumerator()
                     ?? (input as DataRow)?.ItemArray.GetEnumerator()
                     ?? (input as DataRowView)?.Row.ItemArray.GetEnumerator()
                     ?? (input as IListSource)?.GetList()?.GetEnumerator();

            if (ee == null)
            {
                context.AddException("仅支持DataView,DataRow,DataRowView,或实现IEnumerator,IEnumerable,IListSource,IDataReader接口的对象对DataTable的转换");
                success = false;
                return(null);
            }
            var builder = new DataTableBuilder(context);

            builder.TryCreateInstance();
            while (ee.MoveNext())
            {
                if (builder.Set(ee.Current) == false)
                {
                    success = false;
                    return(null);
                }
            }
            return(builder.Instance);
        }