StateManagedCollection 類別

定義

為管理 IStateManager 物件的所有強類型集合,提供基底類別。

public ref class StateManagedCollection abstract : System::Collections::IList, System::Web::UI::IStateManager
public abstract class StateManagedCollection : System.Collections.IList, System.Web.UI.IStateManager
type StateManagedCollection = class
    interface IList
    interface ICollection
    interface IEnumerable
    interface IStateManager
Public MustInherit Class StateManagedCollection
Implements IList, IStateManager
繼承
StateManagedCollection
衍生
實作

範例

下列程式碼範例示範如何從 StateManagedCollection 衍生強型別集合類別,以包含 IStateManager 物件。 在此範例中 CycleCollection ,衍生為 包含抽象 Cycle 類的實例,可以是 BicycleTricycle 物件。 類別 Cycle 會實作 IStateManager 介面,因為它會將屬性的值 CycleColor 儲存在檢視狀態中。

namespace Samples.AspNet.CS.Controls {

    using System;
    using System.Security.Permissions;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;           
    using System.Web;
    using System.Web.UI;            
    //////////////////////////////////////////////////////////////
    //
    // The strongly typed CycleCollection class is a collection
    // that contains Cycle class instances, which implement the
    // IStateManager interface.
    //
    //////////////////////////////////////////////////////////////
    [AspNetHostingPermission(SecurityAction.Demand, 
        Level=AspNetHostingPermissionLevel.Minimal)]
    public sealed class CycleCollection : StateManagedCollection {
        
        private static readonly Type[] _typesOfCycles 
            = new Type[] { typeof(Bicycle), typeof(Tricycle) };

        protected override object CreateKnownType(int index) {
            switch(index) {
                case 0:
                    return new Bicycle();
                case 1:
                    return new Tricycle();                    
                default:
                    throw new ArgumentOutOfRangeException("Unknown Type");
            }            
        }

        protected override Type[] GetKnownTypes() {
            return _typesOfCycles;
        }

        protected override void SetDirtyObject(object o) {
            ((Cycle)o).SetDirty();
        }
    }
    //////////////////////////////////////////////////////////////
    //
    // The abstract Cycle class represents bicycles and tricycles.
    //
    //////////////////////////////////////////////////////////////
    public abstract class Cycle : IStateManager {

        protected internal Cycle(int numWheels) : this(numWheels, "Red"){ }
        
        protected internal Cycle(int numWheels, String color) {    
            numberOfWheels = numWheels;
            CycleColor = color;
        }
        
        private int numberOfWheels = 0;
        public int NumberOfWheels {
            get { return numberOfWheels; }
        }
        
        public string CycleColor {
            get { 
                object o = ViewState["Color"];
                return (null == o) ? String.Empty : o.ToString() ;
            }
            set {
                ViewState["Color"] = value;            
            }        
        }

        internal void SetDirty() {
            ViewState.SetDirty(true);
        }
        
        // Because Cycle does not derive from Control, it does not 
        // have access to an inherited view state StateBag object.
        private StateBag viewState;
        private StateBag ViewState {
            get {
                if (viewState == null) {
                    viewState = new StateBag(false);
                    if (isTrackingViewState) {
                        ((IStateManager)viewState).TrackViewState();
                    }
                }
                return viewState;
            }
        }

        // The IStateManager implementation.
        private bool isTrackingViewState;
        bool IStateManager.IsTrackingViewState {
            get {
                return isTrackingViewState;
            }
        }

        void IStateManager.LoadViewState(object savedState) {
            object[] cycleState = (object[]) savedState;
            
            // In SaveViewState, an array of one element is created.
            // Therefore, if the array passed to LoadViewState has 
            // more than one element, it is invalid.
            if (cycleState.Length != 1) {
                throw new ArgumentException("Invalid Cycle View State");
            }
            
            // Call LoadViewState on the StateBag object.
            ((IStateManager)ViewState).LoadViewState(cycleState[0]);
        }

        // Save the view state by calling the StateBag's SaveViewState
        // method.
        object IStateManager.SaveViewState() {
            object[] cycleState = new object[1];

            if (viewState != null) {
                cycleState[0] = ((IStateManager)viewState).SaveViewState();
            }
            return cycleState;
        }

        // Begin tracking view state. Check the private variable, because 
        // if the view state has not been accessed or set, then it is not  
        // being used and there is no reason to store any view state.
        void IStateManager.TrackViewState() {
            isTrackingViewState = true;
            if (viewState != null) {
                ((IStateManager)viewState).TrackViewState();
            }
        }        
    }

    public sealed class Bicycle : Cycle {
    
        // Create a red Cycle with two wheels.
        public Bicycle() : base(2) {}    
    }
    
    public sealed class Tricycle : Cycle {
    
        // Create a red Cycle with three wheels.
        public Tricycle() : base(3) {}
    }
}
Imports System.Security.Permissions
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Web
Imports System.Web.UI
 
Namespace Samples.AspNet.VB.Controls
    '////////////////////////////////////////////////////////////
    '
    ' The strongly typed CycleCollection class is a collection
    ' that contains Cycle class instances, which implement the
    ' IStateManager interface.
    '
    '////////////////////////////////////////////////////////////
    <AspNetHostingPermission(SecurityAction.Demand, _
        Level:=AspNetHostingPermissionLevel.Minimal)> _
                   Public NotInheritable Class CycleCollection
        Inherits StateManagedCollection

        Private Shared _typesOfCycles() As Type = _
            {GetType(Bicycle), GetType(Tricycle)}

        Protected Overrides Function CreateKnownType(ByVal index As Integer) As Object
            Select Case index
                Case 0
                    Return New Bicycle()
                Case 1
                    Return New Tricycle()
                Case Else
                    Throw New ArgumentOutOfRangeException("Unknown Type")
            End Select

        End Function


        Protected Overrides Function GetKnownTypes() As Type()
            Return _typesOfCycles

        End Function


        Protected Overrides Sub SetDirtyObject(ByVal o As Object)
            CType(o, Cycle).SetDirty()

        End Sub
    End Class
    '////////////////////////////////////////////////////////////
    '
    ' The abstract Cycle class represents bicycles and tricycles.
    '
    '////////////////////////////////////////////////////////////

    MustInherit Public Class Cycle
        Implements IStateManager


        Friend Protected Sub New(ByVal numWheels As Integer) 
            MyClass.New(numWheels, "Red")

        End Sub

        Friend Protected Sub New(ByVal numWheels As Integer, ByVal color As String) 
            numOfWheels = numWheels
            CycleColor = color

        End Sub

        Private numOfWheels As Integer = 0    
        Public ReadOnly Property NumberOfWheels() As Integer 
            Get
                Return numOfWheels
            End Get
        End Property 

        Public Property CycleColor() As String 
            Get
                Dim o As Object = ViewState("Color")
                If o Is Nothing Then 
                    Return String.Empty
                Else  
                    Return o.ToString()
                End If            
            End Get
            Set
                ViewState("Color") = value
            End Set
        End Property


        Friend Sub SetDirty() 
            ViewState.SetDirty(True)

        End Sub

        ' Because Cycle does not derive from Control, it does not 
        ' have access to an inherited view state StateBag object.
        Private cycleViewState As StateBag

        Private ReadOnly Property ViewState() As StateBag 
            Get
                If cycleViewState Is Nothing Then
                    cycleViewState = New StateBag(False)
                    If trackingViewState Then
                        CType(cycleViewState, IStateManager).TrackViewState()
                    End If
                End If
                Return cycleViewState
            End Get
        End Property

        ' The IStateManager implementation.
        Private trackingViewState As Boolean

        ReadOnly Property IsTrackingViewState() As Boolean _
            Implements IStateManager.IsTrackingViewState
            Get
                Return trackingViewState
            End Get
        End Property


        Sub LoadViewState(ByVal savedState As Object) _
            Implements IStateManager.LoadViewState
            Dim cycleState As Object() = CType(savedState, Object())

            ' In SaveViewState, an array of one element is created.
            ' Therefore, if the array passed to LoadViewState has 
            ' more than one element, it is invalid.
            If cycleState.Length <> 1 Then
                Throw New ArgumentException("Invalid Cycle View State")
            End If

            ' Call LoadViewState on the StateBag object.
            CType(ViewState, IStateManager).LoadViewState(cycleState(0))

        End Sub


        ' Save the view state by calling the StateBag's SaveViewState
        ' method.
        Function SaveViewState() As Object Implements IStateManager.SaveViewState
            Dim cycleState(0) As Object

            If Not (cycleViewState Is Nothing) Then
                cycleState(0) = _
                CType(cycleViewState, IStateManager).SaveViewState()
            End If
            Return cycleState

        End Function


        ' Begin tracking view state. Check the private variable, because 
        ' if the view state has not been accessed or set, then it is not being 
        ' used and there is no reason to store any view state.
        Sub TrackViewState() Implements IStateManager.TrackViewState
            trackingViewState = True
            If Not (cycleViewState Is Nothing) Then
                CType(cycleViewState, IStateManager).TrackViewState()
            End If

        End Sub
    End Class


    Public NotInheritable Class Bicycle
        Inherits Cycle


        ' Create a red Cycle with two wheels.
        Public Sub New()
            MyBase.New(2)

        End Sub
    End Class

    Public NotInheritable Class Tricycle
        Inherits Cycle


        ' Create a red Cycle with three wheels.
        Public Sub New()
            MyBase.New(3)

        End Sub
    End Class
End Namespace

備註

類別 StateManagedCollection 是儲存 IStateManager 專案之所有強型別集合的基類,包括 DataControlFieldCollectionParameterCollectionStyleCollectionTreeNodeBindingCollection 和其他專案。 StateManagedCollection集合會管理它自己的狀態,以及它所包含的專案狀態。 因此,呼叫 以 IStateManager.SaveViewState 儲存集合的狀態,以及集合目前包含之所有專案的狀態。

StateManagedCollection 類別 CreateKnownType 衍生時,要考慮的最重要方法是 、 GetKnownTypesOnValidateSetDirtySetDirtyObjectCreateKnownTypeGetKnownTypes 方法可用來將索引儲存在內含專案類型的檢視狀態中。 儲存索引而非完整類型名稱可改善效能。 OnValidate每當操作集合的專案時,就會呼叫 方法,並根據商務規則驗證元素。 方法的實作 OnValidate 目前禁止 null 將物件儲存在集合中;不過,您可以覆寫這個方法,以在衍生類型中定義您自己的驗證行為。 方法 SetDirty 會強制將整個集合序列化為檢視狀態,而不只是序列化自上次載入之後對狀態所做的變更。 方法 SetDirtyObject 是一種抽象方法,您可以實作,以在元素層級執行這個相同的行為。

重要

StateManagedCollection 會以檢視狀態儲存集合專案的元件限定型別名稱。 網站訪客可以解碼檢視狀態,並擷取類型名稱。 如果此案例在您的網站中建立安全性考慮,您可以在將類型名稱置於檢視狀態之前,先手動加密類型名稱。

建構函式

StateManagedCollection()

初始化 StateManagedCollection 類別的新執行個體。

屬性

Count

取得 StateManagedCollection 集合中所包含的項目數。

方法

Clear()

將所有項目從 StateManagedCollection 集合中移除。

CopyTo(Array, Int32)

從特定的陣列索引開始,將 StateManagedCollection 集合的項目複製到陣列。

CreateKnownType(Int32)

在衍生類別中覆寫時,建立實作 IStateManager 之類別的執行個體。 根據 GetKnownTypes() 方法所傳回之集合指定的成員,建立物件的類型。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetEnumerator()

傳回逐一查看 StateManagedCollection 集合的列舉值。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetKnownTypes()

在衍生類別中覆寫時,取得 StateManagedCollection 集合可以包含之 IStateManager 類型的陣列。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnClear()

在衍生類別中覆寫時,在 Clear() 方法移除集合的所有項目之前,執行額外工作。

OnClearComplete()

在衍生類別中覆寫時,在 Clear() 方法完成移除集合的所有項目之後,執行額外工作。

OnInsert(Int32, Object)

在衍生類別中覆寫時,在 IList.Insert(Int32, Object)IList.Add(Object) 方法將項目加入集合之前,執行額外工作。

OnInsertComplete(Int32, Object)

在衍生類別中覆寫時,在 IList.Insert(Int32, Object)IList.Add(Object) 方法將項目加入集合之後,執行額外工作。

OnRemove(Int32, Object)

在衍生類別中覆寫時,在 IList.Remove(Object)IList.RemoveAt(Int32) 方法從集合中移除指定的項目之前,執行額外工作。

OnRemoveComplete(Int32, Object)

在衍生類別中覆寫時,在 IList.Remove(Object)IList.RemoveAt(Int32) 方法從集合中移除指定的項目之後,執行額外工作。

OnValidate(Object)

在衍生類別中覆寫時,驗證 StateManagedCollection 集合的項目。

SetDirty()

強制整個 StateManagedCollection 集合序列化至檢視狀態。

SetDirtyObject(Object)

在衍生類別中覆寫時,指示集合中所包含的 object,將其完整狀態 (而不只是變更資訊) 記錄至檢視狀態。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

明確介面實作

ICollection.Count

取得 StateManagedCollection 集合中所包含的項目數。

ICollection.IsSynchronized

取得值,表示 StateManagedCollection 集合是否為同步 (安全執行緒)。 在所有情況下,這個方法都會傳回 false

ICollection.SyncRoot

取得物件,可用來同步處理對 StateManagedCollection 集合的存取。 在所有情況下,這個方法都會傳回 null

IEnumerable.GetEnumerator()

傳回逐一查看 StateManagedCollection 集合的列舉值。

IList.Add(Object)

將項目加入 StateManagedCollection 集合。

IList.Clear()

將所有項目從 StateManagedCollection 集合中移除。

IList.Contains(Object)

判斷 StateManagedCollection 集合是否包含特定值。

IList.IndexOf(Object)

判斷 StateManagedCollection 集合中指定之項目的索引。

IList.Insert(Int32, Object)

將項目插入位於指定索引處的 StateManagedCollection 集合中。

IList.IsFixedSize

取得值,表示 StateManagedCollection 集合是否具有固定大小。 在所有情況下,這個方法都會傳回 false

IList.IsReadOnly

取得值,表示 StateManagedCollection 集合是否為唯讀。

IList.Item[Int32]

取得指定索引處的 IStateManager 項目。

IList.Remove(Object)

StateManagedCollection 集合中移除指定物件的第一個符合項目。

IList.RemoveAt(Int32)

移除指定索引處的 IStateManager 項目。

IStateManager.IsTrackingViewState

取得值,表示 StateManagedCollection 集合是否正在儲存變更至檢視狀態。

IStateManager.LoadViewState(Object)

還原先前儲存之 StateManagedCollection 集合和內含 IStateManager 項目的檢視狀態。

IStateManager.SaveViewState()

儲存自頁面回傳至伺服器以來 StateManagedCollection 集合和每個內含 IStateManager 物件的變更。

IStateManager.TrackViewState()

使得 StateManagedCollection 集合和每個內含 IStateManager 物件追蹤其檢視狀態的變更,以便跨相同頁面要求保存這些變更。

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。

AsParallel(IEnumerable)

啟用查詢的平行化作業。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

適用於

另請參閱