ConfigComponent学习笔记
请大家关注我的微博:@NormanLin_BadPixel坏像素
这是管理配置信息的组件,我们来看一下配置信息具体是什么。
private Dictionary<Type, ICategory> allConfig;
//////
public interface ICategory: ISupportInitialize
{
Type ConfigType { get; }
}
//////
public interface ISupportInitialize {
void BeginInit();
void EndInit();
}
我们找找ICategory的引用。
ACategory
如作者注释的,这是管理该所有的配置。
protected Dictionary<long, T> dict;
public virtual void BeginInit()
{
this.dict = new Dictionary<long, T>();
string configStr = ConfigHelper.GetText(typeof (T).Name);
foreach (string str in configStr.Split(new[] { "\n" }, StringSplitOptions.None))
{
try
{
string str2 = str.Trim();
if (str2 == "")
{
continue;
}
T t = MongoHelper.FromJson<T>(str2);
this.dict.Add(t.Id, t);
}
catch (Exception e)
{
throw new Exception($"parser json fail: {str}", e);
}
}
}
这里很好理解,通过ConfigHelper.GetText获得到T的配置信息。然后用string.Split分离每一个配置信息,最后,把每一个具体配置信息通过Json反序列化为T对象,储存。
我们以BuffConfig为例。
[Config(AppType.Client)]
public class BuffCategory: ACategory<BuffConfig>
{
}
我们看到,BuffCategory具体存放的配置信息T是BuffConfig。
public class BuffConfig: AConfig
{
public string Name { get; set; }
public int Duration { get; set; }
public BuffConfig()
{
}
public BuffConfig(long id): base(id)
{
}
}
我们看看buffConfig.txt
{ "_id" : 1, "Name": "加速buff", "Duration": 1000 }
{ "_id" : 2, "Name": "增加攻击力buff", "Duration": 1500 }
好理解吧。后面则是一些获取配置信息的各种方法。
ConfigComponent
public void Load()
{
this.allConfig = new Dictionary<Type, ICategory>();
Type[] types = DllHelper.GetMonoTypes();
foreach (Type type in types)
{
object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
if (attrs.Length == 0)
{
continue;
}
object obj = Activator.CreateInstance(type);
ICategory iCategory = obj as ICategory;
if (iCategory == null)
{
throw new Exception($"class: {type.Name} not inherit from ACategory");
}
iCategory.BeginInit();
iCategory.EndInit();
this.allConfig[iCategory.ConfigType] = iCategory;
}
}
知道了ACategory,这里很好解释了,就是从程序集中获取到所有需要加载配置信息的类,然后根据类加载所有的配置信息并储存。后面的各种Get,大家自己理解。
本文详细解析了ConfigComponent组件的工作原理及其实现方式,介绍了如何通过配置文件加载和管理配置信息。

1万+

被折叠的 条评论
为什么被折叠?



