StateManagedCollection 類別

定義

為管理 IStateManager 物件的所有強類型集合,提供基底類別。Provides a base class for all strongly typed collections that manage IStateManager objects.

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 物件。The following code example demonstrates how to derive a strongly typed collection class from StateManagedCollection to contain IStateManager objects. 在此範例中,CycleCollection 衍生為包含抽象 Cycle 類別的實例,可以是 BicycleTricycle 物件。In this example, the CycleCollection is derived to contain instances of the abstract Cycle class, which can be either Bicycle or Tricycle objects. Cycle 類別會執行 IStateManager 介面,因為它會將 CycleColor 屬性的值儲存在 view 狀態中。The Cycle class implements the IStateManager interface because it stores the value of the CycleColor property in view state.

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和其他專案。The StateManagedCollection class is the base class for all strongly typed collections that store IStateManager elements, including DataControlFieldCollection, ParameterCollection, StyleCollection, TreeNodeBindingCollection, and others. StateManagedCollection 集合會管理自己的狀態,以及它所包含之元素的狀態。The StateManagedCollection collection manages its own state as well as the state of the elements it contains. 因此,IStateManager.SaveViewState 的呼叫會儲存集合的狀態,以及集合目前所包含之所有元素的狀態。Therefore, a call to IStateManager.SaveViewState saves the state of the collection and the state of all the elements currently contained by the collection.

StateManagedCollection 類別衍生時,最重要的方法是 CreateKnownTypeGetKnownTypesOnValidateSetDirtySetDirtyObjectThe most important methods to consider when deriving from the StateManagedCollection class are CreateKnownType, GetKnownTypes, OnValidate, SetDirty, and SetDirtyObject. CreateKnownTypeGetKnownTypes 方法是用來針對所包含專案的類型,將索引儲存在檢視狀態中。The CreateKnownType and GetKnownTypes methods are used to store an index in view state for the type of a contained element. 儲存索引而不是完整類型名稱,可以改善效能。Storing an index rather than a fully qualified type name improves performance. 每當操作集合的元素時,就會呼叫 OnValidate 方法,並根據商務規則來驗證元素。The OnValidate method is called whenever elements of the collection are manipulated, and validates the elements according to business rules. 目前,OnValidate 方法的執行會禁止 null 物件儲存在集合中;不過,您可以覆寫這個方法,以在衍生型別中定義您自己的驗證行為。Currently, the implementation of the OnValidate method prohibits null objects from being stored in the collection; however, you can override this method to define your own validation behavior in a derived type. SetDirty 方法會強制將整個集合序列化為 view 狀態,而不只是將自上次載入後對狀態所做的變更序列化。The SetDirty method forces the entire collection to be serialized to view state, rather than just serializing changes made to state since the last time it was loaded. SetDirtyObject 方法是您可以執行的抽象方法,以便在專案層級執行這個相同的行為。The SetDirtyObject method is an abstract method you can implement to perform this same behavior at the element level.

重要

StateManagedCollection 會儲存檢視狀態中收集項的元件限定類型名稱。StateManagedCollection stores assembly-qualified type names of the collection items in view state. 網站訪客可以將檢視狀態解碼,並取出類型名稱。A site visitor could decode the view state and retrieve the type name. 如果這種情況在您的網站中造成安全性問題,您可以手動加密類型名稱,然後才將它放在 view 狀態中。If this scenario creates a security concern in your Web site, you can manually encrypt the type name before placing it in the view state.

建構函式

StateManagedCollection()

初始化 StateManagedCollection 類別的新執行個體。Initializes a new instance of the StateManagedCollection class.

屬性

Count

取得 StateManagedCollection 集合中所包含的項目數。Gets the number of elements contained in the StateManagedCollection collection.

方法

Clear()

將所有項目從 StateManagedCollection 集合中移除。Removes all items from the StateManagedCollection collection.

CopyTo(Array, Int32)

從特定的陣列索引開始,將 StateManagedCollection 集合的項目複製到陣列。Copies the elements of the StateManagedCollection collection to an array, starting at a particular array index.

CreateKnownType(Int32)

在衍生類別中覆寫時,建立實作 IStateManager 之類別的執行個體。When overridden in a derived class, creates an instance of a class that implements IStateManager. 根據 GetKnownTypes() 方法所傳回之集合指定的成員,建立物件的類型。The type of object created is based on the specified member of the collection returned by the GetKnownTypes() method.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetEnumerator()

傳回逐一查看 StateManagedCollection 集合的列舉值。Returns an iterator that iterates through the StateManagedCollection collection.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetKnownTypes()

在衍生類別中覆寫時,取得 StateManagedCollection 集合可以包含之 IStateManager 類型的陣列。When overridden in a derived class, gets an array of IStateManager types that the StateManagedCollection collection can contain.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
OnClear()

在衍生類別中覆寫時,在 Clear() 方法移除集合的所有項目之前,執行額外工作。When overridden in a derived class, performs additional work before the Clear() method removes all items from the collection.

OnClearComplete()

在衍生類別中覆寫時,在 Clear() 方法完成移除集合的所有項目之後,執行額外工作。When overridden in a derived class, performs additional work after the Clear() method finishes removing all items from the collection.

OnInsert(Int32, Object)

在衍生類別中覆寫時,在 IList.Insert(Int32, Object)IList.Add(Object) 方法將項目加入集合之前,執行額外工作。When overridden in a derived class, performs additional work before the IList.Insert(Int32, Object) or IList.Add(Object) method adds an item to the collection.

OnInsertComplete(Int32, Object)

在衍生類別中覆寫時,在 IList.Insert(Int32, Object)IList.Add(Object) 方法將項目加入集合之後,執行額外工作。When overridden in a derived class, performs additional work after the IList.Insert(Int32, Object) or IList.Add(Object) method adds an item to the collection.

OnRemove(Int32, Object)

在衍生類別中覆寫時,在 IList.Remove(Object)IList.RemoveAt(Int32) 方法從集合中移除指定的項目之前,執行額外工作。When overridden in a derived class, performs additional work before the IList.Remove(Object) or IList.RemoveAt(Int32) method removes the specified item from the collection.

OnRemoveComplete(Int32, Object)

在衍生類別中覆寫時,在 IList.Remove(Object)IList.RemoveAt(Int32) 方法從集合中移除指定的項目之後,執行額外工作。When overridden in a derived class, performs additional work after the IList.Remove(Object) or IList.RemoveAt(Int32) method removes the specified item from the collection.

OnValidate(Object)

在衍生類別中覆寫時,驗證 StateManagedCollection 集合的項目。When overridden in a derived class, validates an element of the StateManagedCollection collection.

SetDirty()

強制整個 StateManagedCollection 集合序列化至檢視狀態。Forces the entire StateManagedCollection collection to be serialized into view state.

SetDirtyObject(Object)

在衍生類別中覆寫時,指示集合中所包含的 object,將其完整狀態 (而不只是變更資訊) 記錄至檢視狀態。When overridden in a derived class, instructs an object contained by the collection to record its entire state to view state, rather than recording only change information.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

ICollection.Count

取得 StateManagedCollection 集合中所包含的項目數。Gets the number of elements contained in the StateManagedCollection collection.

ICollection.IsSynchronized

取得值,表示 StateManagedCollection 集合是否為同步 (安全執行緒)。Gets a value indicating whether the StateManagedCollection collection is synchronized (thread safe). 在所有情況下,這個方法都會傳回 falseThis method returns false in all cases.

ICollection.SyncRoot

取得物件,這個物件可以用來對 StateManagedCollection 集合進行同步存取。Gets an object that can be used to synchronize access to the StateManagedCollection collection. 在所有情況下,這個方法都會傳回 nullThis method returns null in all cases.

IEnumerable.GetEnumerator()

傳回逐一查看 StateManagedCollection 集合的列舉值。Returns an iterator that iterates through the StateManagedCollection collection.

IList.Add(Object)

將項目加入 StateManagedCollection 集合。Adds an item to the StateManagedCollection collection.

IList.Clear()

將所有項目從 StateManagedCollection 集合中移除。Removes all items from the StateManagedCollection collection.

IList.Contains(Object)

判斷 StateManagedCollection 集合是否包含特定值。Determines whether the StateManagedCollection collection contains a specific value.

IList.IndexOf(Object)

判斷 StateManagedCollection 集合中指定之項目的索引。Determines the index of a specified item in the StateManagedCollection collection.

IList.Insert(Int32, Object)

將項目插入位於指定索引處的 StateManagedCollection 集合中。Inserts an item into the StateManagedCollection collection at the specified index.

IList.IsFixedSize

取得值,表示 StateManagedCollection 集合是否具有固定大小。Gets a value indicating whether the StateManagedCollection collection has a fixed size. 在所有情況下,這個方法都會傳回 falseThis method returns false in all cases.

IList.IsReadOnly

取得值,表示 StateManagedCollection 集合是否為唯讀。Gets a value indicating whether the StateManagedCollection collection is read-only.

IList.Item[Int32]

取得在指定索引處的 IStateManager 項目。Gets the IStateManager element at the specified index.

IList.Remove(Object)

StateManagedCollection 集合中移除指定物件的第一個符合項目。Removes the first occurrence of the specified object from the StateManagedCollection collection.

IList.RemoveAt(Int32)

移除指定索引處的 IStateManager 項目。Removes the IStateManager element at the specified index.

IStateManager.IsTrackingViewState

取得值,表示 StateManagedCollection 集合是否正在儲存變更至檢視狀態。Gets a value indicating whether the StateManagedCollection collection is saving changes to its view state.

IStateManager.LoadViewState(Object)

還原先前儲存之 StateManagedCollection 集合和內含 IStateManager 項目的檢視狀態。Restores the previously saved view state of the StateManagedCollection collection and the IStateManager items it contains.

IStateManager.SaveViewState()

儲存自頁面回傳至伺服器以來 StateManagedCollection 集合和每個內含 IStateManager 物件的變更。Saves the changes to the StateManagedCollection collection and each IStateManager object it contains since the time the page was posted back to the server.

IStateManager.TrackViewState()

使得 StateManagedCollection 集合和每個內含 IStateManager 物件追蹤其檢視狀態的變更,以便跨相同頁面要求保存這些變更。Causes the StateManagedCollection collection and each of the IStateManager objects it contains to track changes to their view state so they can be persisted across requests for the same page.

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

另請參閱