Add完程序集准备好EventSystem后,Main调用了一个空方法MongoHelper.init()
其目的是为了执行MongoHelper
的静态构造函数进行初始化,类的静态构造函数会在这个类的任何东西被引用前执行。
MongoHelper的静态构造函数
扫描程序集中所有非泛型Entity子类,将他们注册到mongo驱动中
目的是让所有Entity子类能被序列化
static MongoHelper()
{
// 自动注册IgnoreExtraElements
// IgnoreExtraElementsConvention:忽略库中有但是类中没有定义的字段。这个一般用于敏感字段处理
ConventionPack conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);
// 遍历Game所在程序集的所有 非泛型Entity子类
Type[] types = typeof(Game).Assembly.GetTypes();
foreach (Type type in types)
{
// 跳过非Entity子类
if (!type.IsSubclassOf(typeof(Entity)))
{
continue;
}
// 跳过泛型
if (type.IsGenericType)
{
continue;
}
try
{
// 注册后,这个type就可以序列化了
BsonClassMap.LookupClassMap(type);
}
catch (Exception e)
{
Log.Error($"11111111111111111: {type.Name} {e}");
}
}
// 其他一些注册
#if SERVER
BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize<Vector3>());
#else
BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize<Vector4>());
BsonSerializer.RegisterSerializer(typeof(Vector2Int), new StructBsonSerialize<Vector2Int>());
#endif
}
完全的自动化注册,使用者也不需要关心类是否注册了。