游戏蛮牛学习群(纯技术交流,不闲聊):539178957
游戏蛮牛 手机端
开启辅助访问
 找回密码
 注册帐号

扫一扫,访问微社区

首页   >   博客   >   随幻Kaller

C#利用反射实现"游戏中游戏对象数据和数据库中数据对应" ...

个人分类: 数据库 | 2018-5-31 16:15
存到数据库中的字段和自定义类中的字段在交互的时候 通常会有类似以下的代码(当然不光是赋值):
userData.attack = databaseData.attack
userData.health = databaseData.health
userData.magic = databaseData.amagic
.
.
.


这样如果字段多的话 需要写很多代码 很不好

用反射即可解决该问题 
例如 查询一个用户 则从数据库中取到各种字段 然后用反射用数据库字段名去设置自定义类中字段的值
这样 也不用特定的类 只要该类中有该字段 直接赋值 这样 就不会遇到 什么物品表 活动表 角色表等等需要一大堆差不多的代码
都用一套即可 只在逻辑层根据需要分开即可

如果熟悉 hibernate 那么这个东西就不难理解了 

再有 如果插入一个用户 用户类中有不想固化的数据 一种很方便的方法就是:
利用特性 在固化的字段上加上特性 这样 在存入的时候 找到了该字段 发现没有特性 就不储存了

下面是示例代码 希望能给一些需要的人一些帮助

[code]csharpcode:

//数据访问对象 用来直接操控数据库
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace KallerServer.Database
{
    public class DataAccessObject
    {

        string url;

        string databaseIP = "127.0.0.1";
        string userID = "root";
        string userPassword = "123123";
        string database = "Kaller";

        static MySqlConnection con;
        private static DataAccessObject _instance;

        public static DataAccessObject Instance
        {
            get
            {
                if (null == _instance)
                {
                    _instance = new DataAccessObject();
                }
                return _instance;
            }
            // set { DataAccessObject._instance = value; }
        }

        private DataAccessObject()
        {
            url = string.Format("Server={0};User ID={1};Password={2};Database={3};CharSet=utf8;", databaseIP, userID, userPassword, database);

            con = new MySqlConnection(url);
        }
 

        public void OpData(string sql)
        {
            con.Open();

            MySqlCommand mycmd = new MySqlCommand(sql, con);


            if (mycmd.ExecuteNonQuery() > 0)
            {
                Console.WriteLine("op success !");
            }
            else
            {
                Console.WriteLine("op fail !");
            }


            con.Close();
        }

        //返回字典 list
        public List<Dictionary<string, object>> SelectData(string sql)
        {
            //---------------------查询

            con.Open();//开启连接

            MySqlCommand cmd = new MySqlCommand(sql, con);
            MySqlDataReader sdr = cmd.ExecuteReader();

            //所有对象
            List<Dictionary<string, object>> objList = new List<Dictionary<string, object>>();

            int i = 0;
            int memberNum = sdr.FieldCount;
            while (sdr.Read())
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                for (int j = 0; j < memberNum; ++j)
                {

                    dic.Add(sdr.GetName(i), sdr.GetValue(i));

                }
                dic.Add(sdr.GetName(i), sdr[i]);


                objList.Add(dic);
                //Console.WriteLine(sdr["name"].ToString());//这里name可换成相应列
                i++;
            }
            Console.ReadLine();
            con.Close();//关闭连接
            return objList;
        }

        //利用反射返回 对象list
        public List<T> SelectData<T>(string sql) where T : new()
        {
            //---------------------查询

            con.Open();//开启连接

            MySqlCommand cmd = new MySqlCommand(sql, con);
            MySqlDataReader sdr = cmd.ExecuteReader();

            //所有对象
            List<T> objList = new List<T>();

            //int i = 0;
            int memberNum = sdr.FieldCount;

            while (sdr.Read())
            {

                T t = new T();
                for (int j = 0; j < memberNum; ++j)
                {
                    Type objType = t.GetType();
                   
                    FieldInfo info = objType.GetField(sdr.GetName(j));
                    if (info != null)
                    {
                        info.SetValue(t, sdr.GetValue(j));
 
                    }
                  
                }

                objList.Add(t);

            }
           
            con.Close();//关闭连接
            return objList;
        }


    }
}

[code]csharpcode:

////////////////////
//数据访问对象操作层 调用数据访问对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


namespace KallerServer.Database.UserDataDao
{


    public class DataDao
    {
        //public UserData userData;

        //针对特定的类
        //public void Insert(UserData userData)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append(@"insert into t_user_data(account,password,name,moveSpeed,rotateSpeed,attack,defence,health,magic,level) values (");
        //    sb.Append("'" + userData.account + "'" + ",");
        //    sb.Append("'" + userData.password + "'" + ",");
        //    sb.Append("'" + userData.name + "'" + ",");
        //    sb.Append(userData.moveSpeed + ",");
        //    sb.Append(userData.rotateSpeed + ",");
        //    sb.Append(userData.attack + ",");
        //    sb.Append(userData.defence + ",");
        //    sb.Append(userData.health + ",");
        //    sb.Append(userData.magic + ",");
        //    sb.Append(userData.level);
        //    sb.Append(");");
        //    DataAccessObject.Instance.InsertData(sb.ToString());
        //}



        //通用类插入 需要在属性中添加特性 [Persistence]
        public void InsertData(object data)
        {
            StringBuilder sb = new StringBuilder();

            //利用反射获取成员
            Type type = data.GetType();

            //表名
            sb.Append("insert into " + type.Name + "( ");

            System.Reflection.MemberInfo[] infos = type.GetMembers();

            StringBuilder typeStr = new StringBuilder();
            StringBuilder valueStr = new StringBuilder();

            for (int i = 0; i < infos.Length; ++i)
            {
                var customAttrLsit = Attribute.GetCustomAttributes(infos[i], typeof(PersistenceAttribute)) as PersistenceAttribute[];
                if (customAttrLsit != null && customAttrLsit.Length > 0)
                {

                    //这里取到持久化化数据
                    string memberName = infos[i].Name;
                    FieldInfo fInfo = type.GetField(memberName);
                    Type fieldType = fInfo.FieldType;
                    
                    string str = "" + fInfo.GetValue(data);
                    typeStr.Append(memberName + ",");
                    valueStr.Append("'" + str + "'" + ",");
                    Console.WriteLine(str);
                

                }

            }

            sb.Append(typeStr.Remove(typeStr.Length - 1, 1) + " ) values ( " + valueStr.Remove(valueStr.Length - 1, 1) + " ); ");

            DataAccessObject.Instance.OpData(sb.ToString());
            Console.WriteLine("the result is : " + sb);


        }

       
        public void DeleteData(string tName, Dictionary<string, object> conditionDic)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("delete from " + tName);

          

            if (conditionDic != null && conditionDic.Count > 0)
            {
                sb.Append(" where ");
                int i = 0;
                foreach (var item in conditionDic)
                {

                    //默认 and 
                    if (i == conditionDic.Count - 1)
                    {
                        sb.Append(item.Key + " = '" + item.Value + "'");
                    }
                    else
                    {
                        sb.Append(item.Key + " = " + item.Value + " and ");
                    }

                    i++;
                }
            }

            sb.Append(";");

            DataAccessObject.Instance.OpData(sb.ToString());

            Console.WriteLine(sb);

        }




      
        public void UpdateData(string tName, Dictionary<string, object> dic, Dictionary<string, object> conditionDic)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update " + tName + " set ");

            foreach (var item in dic)
            {
                sb.Append(item.Key + " = '" + item.Value + "',");

            }
            sb.Remove(sb.Length - 1, 1);

            if (conditionDic != null && conditionDic.Count > 0)
            {
                sb.Append(" where ");
                int i = 0;
                foreach (var item in conditionDic)
                {

                    //默认 and 
                    if (i == conditionDic.Count - 1)
                    {
                        sb.Append(item.Key + " = '" + item.Value + "'");
                    }
                    else
                    {
                        sb.Append(item.Key + " = " + item.Value + " and ");
                    }

                    i++;
                }
            }

            sb.Append(";");

            DataAccessObject.Instance.OpData(sb.ToString());

            Console.WriteLine(sb);
            
        }


        //查找
        public List<T> SelectData<T>( Dictionary<string, object> conditionDic)where T : new()
        {
            return SelectData<T>(null, conditionDic);
        }
        public List<T> SelectData<T>( List<string> fieldList, Dictionary<string, object> conditionDic) where T : new()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select ");
            StringBuilder fieldName = new StringBuilder();
            if (fieldList != null && fieldList.Count > 0)
            {
                foreach (var item in fieldList)
                {
                    sb.Append(item + ",");

                }
                sb.Remove(sb.Length - 1, 1);
            }
            else
            {
                sb.Append("*");
            }

            sb.Append(" from " + typeof(T).Name + " ");



            if (conditionDic != null && conditionDic.Count > 0)
            {
                sb.Append(" where ");
                int i = 0;
                foreach (var item in conditionDic)
                {

                    //默认 and 
                    if (i == conditionDic.Count - 1)
                    {
                        sb.Append(item.Key + " = '" + item.Value + "'");
                    }
                    else
                    {
                        sb.Append(item.Key + " = " + item.Value + " and ");
                    }

                    i++;
                }
            }

            sb.Append(";");

        

            return DataAccessObject.Instance.SelectData<T>(sb.ToString());

        }


    }
}

[code]csharpcode:

////////////////////////
//服务层 也就是逻辑层
using KallerServer.Database.UserDataDao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KallerServer
{
    public class UserDataService
    {
        DataDao userDao = new DataDao();
        public void InsertUsers(List<UserData> list)
        {

        }
        public void InsertRandomInfoUsers(int num)
        {
            Random r = new Random();
            for (int i = 0; i < num; ++i)
            {
                UserData u = new UserData();
                u.account = "a" + r.Next(num);
                //在这应该判断是否存在该 account
                u.password = "" + u.account;
                u.name = "" + u.account;
                u.moveSpeed = 10 + r.Next(0, 20);
                u.rotateSpeed = 360 + r.Next(0, 180);
                u.attack = 10 + r.Next(0, 20);
                u.defence = 2 + r.Next(0, 5);
                u.health = 100 + r.Next(0, 100);
                u.magic = 50 + r.Next(0, 80);
                u.level = 1;

                userDao.InsertData(u);
            }
        }

        public void InsertUser(UserData u)
        {
            userDao.InsertData(u);
        }

        public void DeleteUser(Dictionary<string, object> conditionDic)
        {
            userDao.DeleteData(typeof(UserData).Name, conditionDic);
        }  


        //目前条件只是 and 需要复杂的话需要扩展
        public void UpdateUser(Dictionary<string, object> valueDic, Dictionary<string, object> conditionDic)
        {
           
            //用 typeof 是因为防止写错
            userDao.UpdateData(typeof(UserData).Name, valueDic, conditionDic);
        }

        public List<UserData> SelectAllUser(Dictionary<string, object> conditionDic)
        {
           
            return userDao.SelectData<UserData>( conditionDic);
            
        }

        public List<UserData> SelectUserData(List<string> list, Dictionary<string, object> conditionDic)
        {

            return userDao.SelectData<UserData>(list, conditionDic);

        }
   

    }
}

[code]csharpcode:

///////////////
//自定义 持久化特性
public class PersistenceAttribute : Attribute
{
    public PersistenceAttribute(string Descrition_in)
    {
        this.description = Descrition_in;
    }
    public PersistenceAttribute()
    {

    }
    protected string description;
    public string Description
    {
        get
        {
            return this.description;
        }
    }
}

//自定义数据
public class UserData
{
    //固化数据
    [Persistence]
    public string account;
    [Persistence]
    public string password;
    [Persistence]
    public string name;

    [Persistence]
    public float moveSpeed;
    [Persistence]
    public float rotateSpeed;

    //攻防血
    [Persistence]
    public float attack;
    [Persistence]
    public float defence;
    [Persistence]
    public float health;
    [Persistence]
    public float magic;
    [Persistence]
    public float level;


    //非固化数据
    float a;
    float b;
    //固化数据操作
    public UserDataService opData;
    public UserData()
    {
 
    }
   

}


[code]csharpcode:

//这里是测试代码
  
            UserDataService op = new UserDataService();
            //插入
           // op.InsertRandomInfoUsers(15);

            //UserData u = new UserData();
            //u.account = "zzz";
            //u.password = "zzz";
            //u.attack = 20;
            //op.InsertUser(u);

            //更新
            //op.UpdateUser(
            //    new Dictionary<string, object>(){
            //    {"attack", 300} },
            //    new Dictionary<string, object>() {
            //    {"account", "a1"} }
            //);

            //查找
            //List<UserData> list = op.SelectAllUser(
            //    new Dictionary<string, object>()
            //    {
            //        {"account","a14"}
            //    });
            //List<UserData> list = op.SelectUserData(
            //    new List<string>() 
            //    {
            //        "health"
            //    },
            //    new Dictionary<string, object>()
            //    {
                   
            //        {"account","a14"}
            //    });

            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.account + " " + item.attack + " " + item.health);
            //}

            op.DeleteUser(new Dictionary<string, object>() 
            {
                {"account","a14"}
            });

0 0

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册帐号

个人分类

标签

阅读排行

评论排行

推荐博客

最新博客

关闭

站长推荐 上一条 /1 下一条

返回顶部