-1
建議在服務結構演員中有一個列表嗎?我正在嘗試將用戶收藏夾保存在用戶演員中。這種情況下最好的方法是什麼?服務結構演員狀態和列表
建議在服務結構演員中有一個列表嗎?我正在嘗試將用戶收藏夾保存在用戶演員中。這種情況下最好的方法是什麼?服務結構演員狀態和列表
是的,只要您將列表視爲不可變的。
狀態管理器檢索方法返回對本地內存中對象的引用。僅在本地存儲器中修改此對象不會導致它被長期保存,因此不會被 保存。從 狀態管理器中檢索並修改對象時,必須將其重新插入狀態爲 的管理器,以便持久保存。
-
以下用戶信息類型演示瞭如何定義一個不可變型 採取的上述建議的優勢。
[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));
}
}