可能会有所帮助。在开始研究StackExchange.Redis时,我也遇到了同样的问题。在我的项目中,我创建了 2 个扩展方法,它们帮助我序列化/反序列化 Redis 数据库的复杂类型。您可以将它们扩展到您的需要。
方法:
public static class RedisUtils
{
//Serialize in Redis format:
public static HashEntry[] ToHashEntries(this object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
return properties.Select(property => new HashEntry(property.Name, property.GetValue(obj).ToString())).ToArray();
}
//Deserialize from Redis format
public static T ConvertFromRedis<T>(this HashEntry[] hashEntries)
{
PropertyInfo[] properties = typeof(T).GetProperties();
var obj = Activator.CreateInstance(typeof(T));
foreach (var property in properties)
{
HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
if (entry.Equals(new HashEntry())) continue;
property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
}
return (T)obj;
}
}
用法:
var customer = new Customer
{
//Initialization
};
Db.HashSet("customer", customer.ToHashEntries());
Customer result = Db.HashGetAll("customer").ConvertFromRedis<Customer>();
Assert.AreEqual(customer.FirstName, result.FirstName);
Assert.AreEqual(customer.LastName, result.LastName);
Assert.AreEqual(customer.Address1, result.Address1);