【Unity 框架】QFramework v1.0 使用指南 工具篇:12. TableKit 表数据结构 | Unity 游戏框架 | Unity 游戏开发 | Unity 独立游戏

在设计 UIKit、ResKit 等系统时,如果只使用默认的 List 和 Dictionary 来管理数据和对象需要做很多的封装。

因为本身 List 和 Dictionary 支持的查询方式比较单一,如果想做一些比较复杂的查询,比如联合查询,那么 List 和 Dictionary 的性能会比较差。

所以为此,笔者简单封装了一个 Table 数据结构。

使用示例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace QFramework
{
    
    
    public class TableKitExample : MonoBehaviour
    {
    
    
        public class Student
        {
    
    
            public string Name {
    
     get; set; }
            public int Age {
    
     get; set; }
            public int Level {
    
     get; set; }
        }
        public class School : Table<Student>
        {
    
    
            public TableIndex<int, Student> AgeIndex = new TableIndex<int, Student>((student) => student.Age);
            public TableIndex<int, Student> LevelIndex = new TableIndex<int, Student>((student) => student.Level);
            
            protected override void OnAdd(Student item)
            {
    
    
                AgeIndex.Add(item);
                LevelIndex.Add(item);
            }

            protected override void OnRemove(Student item)
            {
    
    
                AgeIndex.Remove(item);
                LevelIndex.Remove(item);
            }

            protected override void OnClear()
            {
    
    
                AgeIndex.Clear();
                LevelIndex.Clear();
            }

            public override IEnumerator<Student> GetEnumerator()
            {
    
    
                return AgeIndex.Dictionary.Values.SelectMany(s=>s).GetEnumerator();
            }

            protected override void OnDispose()
            {
    
    
                AgeIndex.Dispose();
                LevelIndex.Dispose();
            }
        }


        private void Start()
        {
    
    
            var school = new School();
            school.Add(new Student(){
    
    Age = 1,Level = 2,Name = "liangxie"});
            school.Add(new Student(){
    
    Age = 2,Level = 2,Name = "ava"});
            school.Add(new Student(){
    
    Age = 3,Level = 2,Name = "abc"});
            school.Add(new Student(){
    
    Age = 3,Level = 3,Name = "efg"});
            
            foreach (var student in school.LevelIndex.Get(2).Where(s=>s.Age < 3))
            {
    
    
                Debug.Log(student.Age + ":" + student.Level + ":" + student.Name);
            }
        }
    }
}
// 1:2:liangxie
// 2:2:ava

TableKit 兼顾查询功能支持和性能,在功能和性能之间取得了一个平衡。

ResKit、UIKit 的数据管理全部由 TableKit 支持。

更多内容

猜你喜欢

转载自blog.csdn.net/u010125551/article/details/127357748