C# 泛型 T 函数,其中 T 来自字符串

C# generic T function where T is from a string

我正在为大型数据库创建设备和服务器之间的同步功能。我有很多列表 tables(dropdown/picker 中的项目)。 我不想写很多代码,我正在寻找一个优雅的解决方案:)

在 SQLite 中的设备上,我定义了清单 table 就像

    public class NameTable : IBusinessEntity {
        public int Id { get; set; } = 0;
        public string Description { get; set; }
    }

当我在数据库中保存一条新记录(项目)时,我调用这个函数

    public int SaveItem<T>(T item) where T : IBusinessEntity {
        lock (locker) {
            if (item.Id != 0) {
                database.Update(item);
                return item.Id;
            }
            else {
                return database.Insert(item);
            }
        }
    }

现在当设备从服务器接收到新记录时,结构如下

    public class SyncResult {
        public int DeviceId { get; set; }
        public int ServerId { get; set; }
        public string TableName { get; set; }
        public string Description { get; set; }
    }

然后我想保存(如果 DeviceId == 0 插入新记录或更新现有项目)。

我的问题是:如何调用 SaveItem 其中 TTableName 来自SyncResult?

提前感谢您的帮助(我可以为此提供啤酒!)


SaveItemMyDatabase class 的成员。基本上我的问题是如何将 T 作为字符串传递给 SaveItem<T>

不知道我有没有把我的问题解释清楚

您可以将 TableName 映射到 Type,例如 Dictionary<string,Type> 使用 Activator class 构造类型。使用反射填充数据。