gpt4 book ai didi

c# - 从 Redis 获取复杂对象时,值为 null

转载 作者:行者123 更新时间:2023-12-03 06:42:43 24 4
gpt4 key购买 nike

我正在尝试将一个复杂的对象添加到 Redis 中,但是在从 Redis 检索值时,我将某些值设为 null。下面是我正在尝试的粗略样本。我有一个复杂对象,我使用 JsonConvert 序列化该复杂对象并将其添加到 Redis 中。属性 CollectionID 有两个具有各自值的计数,但是在从 Redis 和反序列化获取它之后,该值会变为空值。请检查下图

属性 CollectionID 有两个带 ID 的值:

enter image description here

从 Redis 缓存中获取时,该属性变为 null
So

下面是示例:

class Program
{
private static IDatabase _cache;
private static ConnectionMultiplexer _connection;

static void Main(string[] args)
{
_connection = ConnectionMultiplexer.Connect("localhost");
_cache = _connection.GetDatabase();

List<Id> id = new List<Id>() { new Id() { ID = 10 }, new Id() { ID = 20 } };
Collection<Customers> collection = new Collection<Customers>() { new Customers(id) };
Product product = new Product(new Guid(), collection, 1);
_cache.StringSet("Redis_Key", GetSerializedString(product));
var value = JsonConvert.DeserializeObject<Product>(_cache.StringGet("Redis_Key"));
}

private static String GetSerializedString<Test1>(Test1 value)
{
return JsonConvert.SerializeObject(
value,
Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.All
});
}
}

public class Product
{
public Product(
Guid parentGuid,
Collection<Customers> collection,
int number)
{
_parentGuid = parentGuid;
_collection = collection;
_number = number;
}

private Guid _parentGuid;
public Guid ParentGuid
{
get { return _parentGuid; }
}

private Collection<Customers> _collection;
public Collection<Customers> Collection
{
get { return _collection; }
}

private int _number;
public int number
{
get { return _number; }
}
}

public class Customers
{
public Customers(IEnumerable<Id> id)
{
_id = id;
}

private IEnumerable<Id> _id;

public IEnumerable<Id> CollectionID
{
get { return _id; }
}
}

public class Id
{
public int ID { get; set; }
}

任何建议都会有很大帮助。

谢谢,
阿尼什

最佳答案

问题是您在 CollectionID 上没有 setter .

public IEnumerable<Id> CollectionID
{
get { return _id; }
set { _id = value; } //need a setter
}

如果您需要 setter 为 private ,你可以这样做,但你需要一个 ContractResolver .您可以添加包 JsonNet.PrivateSettersContractResolvers , 然后加
using JsonNet.PrivateSettersContractResolvers;
...
var value = JsonConvert.DeserializeObject<Product>(_cache.StringGet("Redis_Key"),
new JsonSerializerSettings
{
ContractResolver = new PrivateSetterContractResolver()
});

Private setters in Json.Net .

关于c# - 从 Redis 获取复杂对象时,值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60002178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com