-1

是否建议在 Service Fabric Actor 中有一个列表?我正在尝试将用户收藏夹保留在用户演员中。这种情况的最佳方法是什么?

4

1 回答 1

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));
   }
}

更多信息:12

于 2017-09-26T06:08:20.553 回答