美文网首页
unity3D,用sqlite中的数据,实例化类

unity3D,用sqlite中的数据,实例化类

作者: 雾再不斩 | 来源:发表于2018-03-16 17:10 被阅读0次

    unity用,用sqlite中的数据,实例化类

    写了一个方法.用反射实例化一个类,并用sqlite的数据为其中属性赋值.

    使用需要一些前提

    1.你需要传入要实例化的类型.

    2.你需要将实例化使用的数据读取到一个SqliteDataReader中.

    这是github代码,实际运行下可能更好理解.https://github.com/943670930/DB2Entity

    实际代码:

    /// 

        /// Creates the object.

        /// 读取reader中数据,用数据实例化一个类

        /// 

        /// The object.

        /// Sq reader.

        /// The 1st type parameter.

        public T CreateObject(SqliteDataReader sqReader){

            //实例化一个空类

            T newObject = System.Activator.CreateInstance();

            //获取类型

            Type type = newObject.GetType ();

            //获取类型中所有public属性

            FieldInfo[] fields =  type.GetFields ();//BindingFlags.Public);

            //遍历所有属性

            foreach (FieldInfo field in fields) {

                string attrName = field.Name;//获取属性名

                int colIndex = sqReader.GetOrdinal (attrName);//获取这个属性在reader中的位置

                //从reader中取值

                object newValue = new object();

                if(field.FieldType == typeof(int)){

                    newValue = sqReader.GetInt32 (colIndex);

                }else if(field.FieldType == typeof(string)){

                    newValue = sqReader.GetString (colIndex);

                }

                //赋值给属性

                type.GetField (attrName).SetValue (newObject,newValue);

            }

            return newObject;

        }

    有问题可以联系我微博@圆滚滚骑士

    相关文章

      网友评论

          本文标题:unity3D,用sqlite中的数据,实例化类

          本文链接:https://www.haomeiwen.com/subject/jydrqftx.html