Mono Android中能否通过参数(字符串)获取Type以动态创建SQLite表?
解决Android Mono中动态调用SQLite CreateTable的问题
嘿,我之前在做Mono Android项目用SQLite的时候也遇到过这个头疼的问题——泛型方法CreateTable<T>没法直接用Type变量来动态调用对吧?给你两个实用的解决方案,看哪个更适配你的场景:
方案一:通过反射调用泛型方法
如果你的SQLite-Net版本没有提供非泛型的CreateTable重载,反射是最直接的办法。不管你传入的是Type对象还是表名字符串,都能转成对应的类型后调用泛型方法:
using System; using System.Reflection; using SQLite; public class DbHelper { // 接收Type参数的版本 public void CreateDynamicTable(SQLiteConnection sqlite, Type tableType) { // 获取CreateTable泛型方法的定义(无参数重载) MethodInfo createTableMethod = typeof(SQLiteConnection) .GetMethod("CreateTable", Type.EmptyTypes); // 构造对应类型的泛型方法实例 MethodInfo genericCreateTable = createTableMethod.MakeGenericMethod(tableType); // 执行方法 genericCreateTable.Invoke(sqlite, null); } // 接收表名字符串的版本 public void CreateDynamicTable(SQLiteConnection sqlite, string tableTypeName) { // 将字符串转换为Type,注意如果类型不在当前程序集,要传入完整的类型名(包含程序集) Type tableType = Type.GetType(tableTypeName); if (tableType == null) { throw new ArgumentException($"找不到指定的类型:{tableTypeName},请检查类型名是否正确,或者传入完整的程序集限定名"); } CreateDynamicTable(sqlite, tableType); } }
注意事项
- 用
Type.GetType的时候,如果你的实体类在另一个程序集里,需要传入完整的类型名,比如"MyApp.Models.User, MyApp",不然会返回null。 - 如果
CreateTable有多个重载(比如带CreateFlags参数的),记得在GetMethod里指定参数类型来匹配正确的重载。
方案二:使用非泛型的CreateTable重载
如果你用的是较新版本的SQLite-Net,其实官方已经提供了直接接收Type参数的非泛型CreateTable方法,这样就完全不用反射了,代码更简洁:
using System; using SQLite; public class DbHelper { public void CreateDynamicTable(SQLiteConnection sqlite, Type tableType) { // 直接调用非泛型重载 sqlite.CreateTable(tableType); } public void CreateDynamicTable(SQLiteConnection sqlite, string tableTypeName) { Type tableType = Type.GetType(tableTypeName); if (tableType != null) { sqlite.CreateTable(tableType); } else { // 自定义错误处理逻辑,比如日志、抛出异常等 throw new ArgumentException($"无效的表类型名称:{tableTypeName}"); } } }
小提示
可以先检查你的SQLite-Net NuGet包版本,或者查看SQLiteConnection的API文档,确认是否存在CreateTable(Type)这个重载。如果没有,升级到最新稳定版应该就能用了。
这两个方案都能满足你动态创建表的需求,根据你的项目环境选就行!
内容的提问来源于stack exchange,提问作者Valentino Gechev
相关产品推荐
相关产品推荐

