2017-09-25 43 views

回答

2

是的,只要您將列表視爲不可變的。

狀態管理器檢索方法返回對本地內存中對象的引用。僅在本地存儲器中修改此對象不會導致它被長期保存,因此不會被 保存。從 狀態管理器中檢索並修改對象時,必須將其重新插入狀態爲 的管理器,以便持久保存。

-

以下用戶信息類型演示瞭如何定義一個不可變型 採取的上述建議的優勢。

[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