是否建议在Service Fabric actor中有一个列表?我想在用户角色中保留用户收藏夹。这种情况的最佳方法是什么?
答案 0 :(得分:2)
是的,只要您将列表视为不可变。
状态管理器检索方法返回对象中的对象的引用 本地记忆。仅在本地内存中修改此对象不会 使它得以持久保存。从中检索对象时 国家经理和修改后,必须重新插入州 经理要永远得救。
-
下面的UserInfo类型演示了如何定义不可变类型 利用上述建议。
[DataContract]
// If you don’t seal, you must ensure that any derived classes are also immutable
public sealed class UserInfo {
private static readonly IEnumerable<ItemId> NoBids = ImmutableList<ItemId>.Empty;
public UserInfo(String email, IEnumerable<ItemId> itemsBidding = null) {
Email = email;
ItemsBidding = (itemsBidding == null) ? NoBids : itemsBidding.ToImmutableList();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context) {
// Convert the deserialized collection to an immutable collection
ItemsBidding = ItemsBidding.ToImmutableList();
}
[DataMember]
public readonly String Email;
// Ideally, this would be a readonly field but it can't be because OnDeserialized
// has to set it. So instead, the getter is public and the setter is private.
[DataMember]
public IEnumerable<ItemId> ItemsBidding { get; private set; }
// Since each UserInfo object is immutable, we add a new ItemId to the ItemsBidding
// collection by creating a new immutable UserInfo object with the added ItemId.
public UserInfo AddItemBidding(ItemId itemId) {
return new UserInfo(Email, ((ImmutableList<ItemId>)ItemsBidding).Add(itemId));
}
}