ConfigurationCollectionAttribute ConfigurationCollectionAttribute ConfigurationCollectionAttribute ConfigurationCollectionAttribute Class

定義

.NET Framework が構成要素のコレクションのインスタンスを作成するように、宣言によって指示します。Declaratively instructs the .NET Framework to create an instance of a configuration element collection. このクラスは継承できません。This class cannot be inherited.

public ref class ConfigurationCollectionAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute
type ConfigurationCollectionAttribute = class
    inherit Attribute
Public NotInheritable Class ConfigurationCollectionAttribute
Inherits Attribute
継承
ConfigurationCollectionAttributeConfigurationCollectionAttributeConfigurationCollectionAttributeConfigurationCollectionAttribute
属性

を使用ConfigurationCollectionAttributeする方法を次の例に示します。The following example shows how to use the ConfigurationCollectionAttribute.

この例はUrlsSection、、、 UrlsCollectionおよびの 3 UrlConfigElementつのクラスで構成されています。クラスUrlsSectionは、をConfigurationCollectionAttribute使用してカスタム構成セクションを定義します。This example consists of three classes: UrlsSection, UrlsCollection and UrlConfigElement.The UrlsSection class uses the ConfigurationCollectionAttribute to define a custom configuration section. このセクションには、( UrlsCollection UrlConfigElementクラスで定義された) url 要素の url コレクション (クラスで定義) が含まれています。This section contains a URL collection (defined by the UrlsCollection class) of URL elements (defined by the UrlConfigElement class). この例を実行すると、 UrlsSectionクラスのインスタンスが作成され、次の構成要素がアプリケーション構成ファイルに生成されます。When you run the example, an instance of the UrlsSection class is created and the following configuration elements are generated in the application configuration file:

<configuration>  
    <configSections>  
        <section name="MyUrls" type="UrlsSection,   
          ConfigurationCollectionAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <MyUrls>  
        <urls>  
            <remove name="Contoso" />  
            <add name="Contoso" url="http://www.contoso.com" port="0" />  
        </urls>  
    </MyUrls>  
</configuration  

using System;
using System.Configuration;


// Define a custom section that contains a custom
// UrlsCollection collection of custom UrlConfigElement elements.
// This class shows how to use the ConfigurationCollectionAttribute.
public class UrlsSection : ConfigurationSection
{
    // Declare the Urls collection property using the
    // ConfigurationCollectionAttribute.
    // This allows to build a nested section that contains
    // a collection of elements.
    [ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public UrlsCollection Urls
    {
        get
        {
            UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];
            return urlsCollection;
        }
    }

}

// Define the custom UrlsCollection that contains the 
// custom UrlsConfigElement elements.
public class UrlsCollection : ConfigurationElementCollection
{
    public UrlsCollection()
    {
        UrlConfigElement url = (UrlConfigElement)CreateNewElement();
        Add(url);
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new UrlConfigElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((UrlConfigElement)element).Name;
    }

    public UrlConfigElement this[int index]
    {
        get
        {
            return (UrlConfigElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    new public UrlConfigElement this[string Name]
    {
        get
        {
            return (UrlConfigElement)BaseGet(Name);
        }
    }

    public int IndexOf(UrlConfigElement url)
    {
        return BaseIndexOf(url);
    }

    public void Add(UrlConfigElement url)
    {
        BaseAdd(url);
    }
    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);
    }

    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
            BaseRemove(url.Name);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }
}

// Define the custom UrlsConfigElement elements that are contained 
// by the custom UrlsCollection.
// Notice that you can change the default values to create new default elements.
public class UrlConfigElement : ConfigurationElement
{
    public UrlConfigElement(String name, String url)
    {
        this.Name = name;
        this.Url = url;
    }

    public UrlConfigElement()
    {

        this.Name = "Contoso";
        this.Url = "http://www.contoso.com";
        this.Port = 0;
    }

    [ConfigurationProperty("name", DefaultValue = "Contoso",
        IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}


Imports System.Configuration




' Define a custom section that contains a custom
' UrlsCollection collection of custom UrlConfigElement elements.
' This class shows how to use the ConfigurationCollectionAttribute.
Public Class UrlsSection
	Inherits ConfigurationSection
    ' Declare the Urls collection property using the
    ' ConfigurationCollectionAttribute.
    ' This allows to build a nested section that contains
    ' a collection of elements.
    <ConfigurationProperty("urls", IsDefaultCollection:=False),
        System.Configuration.ConfigurationCollection(GetType(UrlsCollection),
        AddItemName:="add", ClearItemsName:="clear", RemoveItemName:="remove")> _
    Public ReadOnly Property Urls() As UrlsCollection
        Get
            Dim urlsCollection As UrlsCollection = CType(MyBase.Item("urls"), UrlsCollection)
            Return urlsCollection
        End Get
    End Property

End Class

' Define the custom UrlsCollection that contains the 
' custom UrlsConfigElement elements.
Public Class UrlsCollection
    Inherits ConfigurationElementCollection
    Public Sub New()
        Dim url As UrlConfigElement = CType(CreateNewElement(), UrlConfigElement)
        Add(url)
    End Sub

    Public Overrides ReadOnly Property CollectionType() As ConfigurationElementCollectionType
        Get
            Return ConfigurationElementCollectionType.AddRemoveClearMap
        End Get
    End Property

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return New UrlConfigElement()
    End Function

    Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, UrlConfigElement)).Name
    End Function

    Default Shadows Property Item(ByVal index As Integer) As UrlConfigElement
        Get
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If BaseGet(index) IsNot Nothing Then
                BaseRemoveAt(index)
            End If
            BaseAdd(index, value)
        End Set
    End Property

    Default Public Shadows ReadOnly Property Item(ByVal Name As String) As UrlConfigElement
        Get
            Return CType(BaseGet(Name), UrlConfigElement)
        End Get
    End Property

    Public Function IndexOf(ByVal url As UrlConfigElement) As Integer
        Return BaseIndexOf(url)
    End Function

    Public Sub Add(ByVal url As UrlConfigElement)
        BaseAdd(url)
    End Sub
    Protected Overloads Overrides Sub BaseAdd(ByVal element As ConfigurationElement)
        BaseAdd(element, False)
    End Sub

    Public Sub Remove(ByVal url As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
            BaseRemove(url.Name)
        End If
    End Sub

    Public Sub RemoveAt(ByVal index As Integer)
        BaseRemoveAt(index)
    End Sub

    Public Sub Remove(ByVal name As String)
        BaseRemove(name)
    End Sub

    Public Sub Clear()
        BaseClear()
    End Sub
End Class

' Define the custom UrlsConfigElement elements that are contained 
' by the custom UrlsCollection.
Public Class UrlConfigElement
    Inherits ConfigurationElement
    Public Sub New(ByVal name As String, ByVal url As String)
        Me.Name = name
        Me.Url = url
    End Sub

    Public Sub New()
        Me.Name = "Contoso"
        Me.Url = "http://www.contoso.com"
        Me.Port = 0
    End Sub

    <ConfigurationProperty("name", DefaultValue:="Contoso", IsRequired:=True, IsKey:=True)> _
    Public Property Name() As String
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = value
        End Set
    End Property

    <ConfigurationProperty("url", DefaultValue:="http://www.contoso.com", IsRequired:=True),
        RegexStringValidator("\w+:\/\/[\w.]+\S*")> _
    Public Property Url() As String
        Get
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = value
        End Set
    End Property

    <ConfigurationProperty("port", DefaultValue:=0, IsRequired:=False),
        IntegerValidator(MinValue:=0, MaxValue:=8080, ExcludeRange:=False)> _
    Public Property Port() As Integer
        Get
            Return CInt(Fix(Me("port")))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property
End Class

using System;
using System.Configuration;


class UsingConfigurationCollectionAttribute
{

    // Create a custom section and save it in the 
    // application configuration file.
    static void CreateCustomSection()
    {
        try
        {

            // Create a custom configuration section.
            UrlsSection myUrlsSection = new UrlsSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Add the custom section to the application
            // configuration file.
            if (config.Sections["MyUrls"] == null)
            {
                config.Sections.Add("MyUrls", myUrlsSection);
            }

           
            // Save the application configuration file.
            myUrlsSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }

    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection myUrlsSection =
               ConfigurationManager.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
                Console.WriteLine("Failed to load UrlsSection.");
            else
            {
                Console.WriteLine("URLs defined in the configuration file:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("  Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }
          
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }

    }
    
    static void Main(string[] args)
    {
       
        // Get the name of the application.
        string appName =
            Environment.GetCommandLineArgs()[0];

        // Create a custom section and save it in the 
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine();
        Console.WriteLine("Enter any key to exit.");

        Console.ReadLine();
    }
}
Imports System.Configuration


Friend Class UsingConfigurationCollectionAttribute

	' Create a custom section and save it in the 
	' application configuration file.
	Private Shared Sub CreateCustomSection()
		Try

			' Create a custom configuration section.
			Dim myUrlsSection As New UrlsSection()

			' Get the current configuration file.
            Dim config As System.Configuration.Configuration =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

			' Add the custom section to the application
			' configuration file.
			If config.Sections("MyUrls") Is Nothing Then
				config.Sections.Add("MyUrls", myUrlsSection)
			End If


			' Save the application configuration file.
			myUrlsSection.SectionInformation.ForceSave = True
			config.Save(ConfigurationSaveMode.Modified)

			Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath)
			Console.WriteLine()

		Catch err As ConfigurationErrorsException
			Console.WriteLine("CreateCustomSection: {0}", err.ToString())
		End Try

	End Sub

	Private Shared Sub ReadCustomSection()
		Try
			' Get the application configuration file.
			Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

			' Read and display the custom section.
			Dim myUrlsSection As UrlsSection = TryCast(ConfigurationManager.GetSection("MyUrls"), UrlsSection)

			If myUrlsSection Is Nothing Then
				Console.WriteLine("Failed to load UrlsSection.")
			Else
				Console.WriteLine("URLs defined in app.config:")
				For i As Integer = 0 To myUrlsSection.Urls.Count - 1
					Console.WriteLine("  Name={0} URL={1} Port={2}", myUrlsSection.Urls(i).Name, myUrlsSection.Urls(i).Url, myUrlsSection.Urls(i).Port)
				Next i
			End If
        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
		End Try

	End Sub

	Shared Sub Main(ByVal args() As String)

		' Get the name of the application.
		Dim appName As String = Environment.GetCommandLineArgs()(0)

		' Create a custom section and save it in the 
		' application configuration file.
		CreateCustomSection()

		' Read the custom section saved in the
		' application configuration file.
		ReadCustomSection()

        Console.WriteLine()
        Console.WriteLine("Enter any key to exit.")

		Console.ReadLine()
	End Sub
End Class

注釈

要素をConfigurationCollectionAttribute ConfigurationElementCollection修飾するには、属性を使用します。You use the ConfigurationCollectionAttribute attribute to decorate a ConfigurationElementCollection element. これにより、.NET Framework は、コレクションのインスタンスを作成し、カスタムConfigurationElement値を使用してそれを初期化するように指示します。This instructs the .NET Framework to create an instance of the collection and to initialize it using your custom ConfigurationElement values.

注意

カスタム構成要素を作成する最も簡単な方法は、属性付きの (宣言型の) モデルを使用することです。The simplest way to create a custom configuration element is to use the attributed (declarative) model. 要素を宣言し、 ConfigurationCollectionAttribute属性で装飾します。You declare the elements and decorate them with the ConfigurationCollectionAttribute attribute. この属性でマークされた要素ごとに、.NET Framework はリフレクションを使用して装飾パラメーターをConfigurationElementCollection読み取り、関連するインスタンスを作成します。For each element marked with this attribute, the .NET Framework uses reflection to read the decorating parameters and create a related ConfigurationElementCollection instance. プログラムモデルを使用することもできます。You can also use the programmatic model. この場合は、カスタムパブリックコレクションを宣言する必要がありますが、 ConfigurationElementCollectionメンバーをオーバーライドしてプロパティのコレクションを返すこともできます。In this case it is your responsibility to declare the custom public collection but also to override the ConfigurationElementCollection member and return the properties collection.

.NET Framework 構成システムには、カスタム構成要素の作成時に使用できる属性の型が用意されています。The .NET Framework configuration system provides attribute types that you can use during the creation of custom configuration elements. 属性には、次の2種類があります。There are two kinds of attributes:

コンストラクター

ConfigurationCollectionAttribute(Type) ConfigurationCollectionAttribute(Type) ConfigurationCollectionAttribute(Type) ConfigurationCollectionAttribute(Type)

ConfigurationCollectionAttribute クラスの新しいインスタンスを初期化します。Initializes a new instance of the ConfigurationCollectionAttribute class.

プロパティ

AddItemName AddItemName AddItemName AddItemName

<add> 構成要素の名前を取得または設定します。Gets or sets the name of the <add> configuration element.

ClearItemsName ClearItemsName ClearItemsName ClearItemsName

<clear> 構成要素の名前を取得または設定します。Gets or sets the name for the <clear> configuration element.

CollectionType CollectionType CollectionType CollectionType

ConfigurationCollectionAttribute 属性の型を取得または設定します。Gets or sets the type of the ConfigurationCollectionAttribute attribute.

ItemType ItemType ItemType ItemType

コレクション要素の型を取得します。Gets the type of the collection element.

RemoveItemName RemoveItemName RemoveItemName RemoveItemName

<remove> 構成要素の名前を取得または設定します。Gets or sets the name for the <remove> configuration element.

TypeId TypeId TypeId TypeId

派生クラスで実装されると、この Attribute の一意の識別子を取得します。When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

メソッド

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

このインスタンスが、指定されたオブジェクトと等価であるかどうかを示す値を返します。Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

このインスタンスのハッシュ コードを返します。Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

派生クラスでオーバーライドされるとき、このインスタンスの値が派生クラスの既定値であるかどうかを示します。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

派生クラス内でオーバーライドされたときに、指定したオブジェクトとこのインスタンスが等しいかどうかを示す値を返します。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

現在のオブジェクトを表す文字列を返します。Returns a string that represents the current object.

(Inherited from Object)

明示的なインターフェイスの実装

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

一連の名前を対応する一連のディスパッチ識別子に割り当てます。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

オブジェクトの型情報を取得します。この情報はインターフェイスの型情報の取得に使用できます。Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

オブジェクトが提供する型情報インターフェイスの数 (0 または 1) を取得します。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

オブジェクトによって公開されたプロパティおよびメソッドへのアクセスを提供します。Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

適用対象

こちらもご覧ください