使用泛型从对象获取基元类型

本文关键字:类型 获取 对象 泛型 | 更新日期: 2023-09-27 18:35:24

我需要将键值对存储在数据库中。值可以是以下类型之一:boolintdoublestringDateTime。在下面的类中,Set<T> -操作有效,但Get<T>抛出InvalidCastException

public class PersistedKeyValueStorage
{
    AppDbContext _dbContext;
    public PersistedKeyValueStorage() : this(new AppDbContext()) { }
    public PersistedKeyValueStorage(AppDbContext dbContext)
    {
        _dbContext = dbContext; 
    }
    public T Get<T>(string Key) {
        var record=_dbContext.Set<StoredKeyValueItem>().FirstOrDefault(p => p.Key == Key);
        if (record != null) return (T)(object)(record.Value); // here is error
            return default(T);                
    }
    public void Set<T>(string Key, T Value) where T : struct            
    {
        var record = _dbContext.Set<StoredKeyValueItem>().FirstOrDefault(p => p.Key == Key);
        if (record != null) record.Value = Value.ToString();
        else _dbContext.Set<StoredKeyValueItem>().Add(new StoredKeyValueItem { Key = Key, Value = Value.ToString() });
        _dbContext.SaveChanges();
    }
}
// class usage
var skvs = new PersistedKeyValueStorage();
skvs.Set("test.int", (int)123);
skvs.Set("test.boolean", true);
skvs.Set("test.datetime", DateTime.Now);
ViewBag.testint= skvs.Get<int>("test.int");
ViewBag.testbool = skvs.Get<Boolean>("test.boolean");
ViewBag.testdate= skvs.Get<DateTime>("test.datetime");

使用泛型从对象获取基元类型

您将所有值作为字符串存储在存储中。

所以当你把它们拿回来时,它们将是字符串。

要从objectT,则实际对象必须是:

  • 类型为 T 的值类型
  • 可重新解释为 T 的引用类型

int是一种值类型,但是在执行(int)obj时,您只能将里面的值拆箱,并且它必须是int。在您的情况下,这是一个string。这是行不通的。

相反,您必须使用转换层来回转换您的存储类型,在这种情况下string

对于某些类型,您可以尝试将代码更改为以下内容:

return (T)Convert.ChangeType(record.Value, typeof(T));

但这不会处理所有符合T条件的类型。