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 강력한 형식의 모든 컬렉션(예DataControlFieldCollection: , ParameterCollectionStyleCollectionTreeNodeBindingCollection기타)의 기본 클래스입니다. 컬렉션은 StateManagedCollection 포함된 요소의 상태뿐만 아니라 자체 상태를 관리합니다. 따라서 컬렉션의 상태 및 컬렉션에 현재 포함 된 모든 요소의 상태를 저장 하는 IStateManager.SaveViewState 호출 합니다.

클래스에서 StateManagedCollection 파생할 때 고려해야 할 가장 중요한 메서드는 CreateKnownType, GetKnownTypes, OnValidateSetDirtySetDirtyObject. 및 CreateKnownType 메서드는 GetKnownTypes 포함된 요소의 형식에 대한 인덱스 뷰 상태를 저장하는 데 사용됩니다. 정규화된 형식 이름이 아닌 인덱스를 저장하면 성능이 향상됩니다. 이 OnValidate 메서드는 컬렉션의 요소가 조작될 때마다 호출되며 비즈니스 규칙에 따라 요소의 유효성을 검사합니다. 현재 메서드 OnValidate 를 구현하면 개체가 컬렉션에 저장되지 않습니다. 그러나 이 메서드를 재정의 null 하여 파생 형식에서 사용자 고유의 유효성 검사 동작을 정의할 수 있습니다. 이 메서드는 SetDirty 마지막으로 로드된 이후의 상태 변경 내용을 직렬화하는 대신 전체 컬렉션을 직렬화하여 상태를 표시하도록 합니다. 이 SetDirtyObject 메서드는 요소 수준에서 이 동일한 동작을 수행하기 위해 구현할 수 있는 추상 메서드입니다.

Important

StateManagedCollection 는 컬렉션 항목의 어셈블리 정규화된 형식 이름을 뷰 상태로 저장합니다. 사이트 방문자는 뷰 상태를 디코딩하고 형식 이름을 검색할 수 있습니다. 이 시나리오로 인해 웹 사이트에서 보안 문제가 발생할 경우 보기 상태에 배치하기 전에 형식 이름을 수동으로 암호화할 수 있습니다.

생성자

Name Description
StateManagedCollection()

StateManagedCollection 클래스의 새 인스턴스를 초기화합니다.

속성

Name Description
Count

컬렉션에 포함된 StateManagedCollection 요소 수를 가져옵니다.

메서드

Name Description
Clear()

컬렉션에서 모든 항목을 제거합니다 StateManagedCollection .

CopyTo(Array, Int32)

특정 배열 인덱스에서 시작하여 컬렉션의 StateManagedCollection 요소를 배열에 복사합니다.

CreateKnownType(Int32)

파생 클래스에서 재정의되는 경우 구현하는 클래스의 인스턴스를 만듭니다 IStateManager. 만든 개체의 형식은 메서드에서 반환된 컬렉션의 지정된 멤버를 기반으로 합니다 GetKnownTypes() .

Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
GetEnumerator()

컬렉션을 반복하는 반복기를 반환합니다 StateManagedCollection .

GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetKnownTypes()

파생 클래스에서 재정의되는 경우 컬렉션에 포함될 수 있는 형식의 IStateManager 배열을 StateManagedCollection 가져옵니다.

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)

명시적 인터페이스 구현

Name Description
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 동일한 페이지에 대한 요청 간에 유지될 수 있도록 해당 뷰 상태의 변경 내용을 추적하도록 합니다.

확장명 메서드

Name Description
AsParallel(IEnumerable)

쿼리의 병렬 처리를 사용하도록 설정합니다.

AsQueryable(IEnumerable)

IEnumerable IQueryable변환합니다.

Cast<TResult>(IEnumerable)

IEnumerable 요소를 지정된 형식으로 캐스팅합니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable 요소를 필터링합니다.

적용 대상

추가 정보