ConfigurationPropertyAttribute クラス

定義

.NET が構成プロパティをインスタンス化するように、宣言によって指示します。 このクラスは継承できません。

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

次の例は、 属性を使用してカスタム ConfigurationSection オブジェクトのプロパティを定義する方法を ConfigurationPropertyAttribute 示しています。

この例には、2 つのクラスが含まれています。 カスタム クラスでは UrlsSection 、 を ConfigurationPropertyAttribute 使用して独自のプロパティを定義します。 クラスでは UsingConfigurationPropertyAttribute 、 を UrlsSection 使用して、アプリケーション構成ファイルのカスタム セクションの読み取りと書き込みを行います。

using System;
using System.Configuration;

// Define a custom section.
// This class shows how to use the ConfigurationPropertyAttribute.
public class UrlsSection : ConfigurationSection
{
    [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.
' This class shows how to use the ConfigurationPropertyAttribute.
Public Class UrlsSection
    Inherits ConfigurationSection
    <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;

public class UsingConfigurationPropertyAttribute
{

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

            // Create a custom configuration section.
            UrlsSection customSection = 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["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Save the application configuration file.
            customSection.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 customSection =
                config.GetSection("CustomSection") as UrlsSection;
            Console.WriteLine("Reading custom section from the configuration file.");
            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
            Console.WriteLine();
        }
        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("Press enter to exit.");

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

Public Class UsingConfigurationPropertyAttribute

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

            ' Create a custom configuration section.
            Dim customSection 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("CustomSection") Is Nothing Then
                config.Sections.Add("CustomSection", customSection)
            End If


            ' Save the application configuration file.
            customSection.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 customSection As UrlsSection = TryCast(config.GetSection("CustomSection"), UrlsSection)
            Console.WriteLine("Reading custom section from the configuration file.")
            Console.WriteLine("Section name: {0}", customSection.Name)
            Console.WriteLine("Url: {0}", customSection.Url)
            Console.WriteLine("Port: {0}", customSection.Port)
            Console.WriteLine()
        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("Press enter to exit.")

        Console.ReadLine()
    End Sub
End Class

前のサンプルで定義したカスタム セクションを含む構成ファイルの抜粋を次に示します。

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
    <configSections>  
        <section name="CustomSection" type="UrlsSection, UsingConfigurationPropertyAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <CustomSection name="Contoso" url="http://www.contoso.com" />  
</configuration>  

注釈

を使用 ConfigurationPropertyAttribute して構成プロパティを装飾します。これにより、.NET に対して、装飾パラメーターの値を使用して、インスタンス化とプロパティの初期化を指示します。

注意

カスタム構成要素を作成する最も簡単な方法は、属性付き (宣言型) モデルを使用することです。 カスタム パブリック プロパティを宣言し、 属性で ConfigurationPropertyAttribute 装飾します。 この属性でマークされた各プロパティについて、.NET はリフレクションを使用して装飾パラメーターを読み取り、関連する ConfigurationProperty インスタンスを作成します。 プログラム モデルを使用することもできます。その場合は、カスタム パブリック プロパティを宣言し、そのコレクションを返す必要があります。

.NET 構成システムには、カスタム構成要素の作成時に使用できる属性型が用意されています。 属性の型には、次の 2 種類があります。

  1. カスタム構成要素のプロパティをインスタンス化する方法を .NET に指示する型。 型には次のものがあります。

  2. カスタム構成要素プロパティの検証方法を .NET に指示する型。 型には次のものがあります。

コンストラクター

ConfigurationPropertyAttribute(String)

ConfigurationPropertyAttribute クラスの新しいインスタンスを初期化します。

プロパティ

DefaultValue

装飾されたプロパティの既定値を取得または設定します。

IsDefaultCollection

これが、装飾された構成プロパティに対する既定プロパティのコレクションかどうかを示す値を取得または設定します。

IsKey

これが、装飾された要素のプロパティに対する主要プロパティかどうかを示す値を取得または設定します。

IsRequired

装飾された要素のプロパティが必要かどうかを示す値を取得または設定します。

Name

装飾された構成要素のプロパティの名前を取得します。

Options

装飾された構成要素のプロパティの ConfigurationPropertyOptions を取得または設定します。

TypeId

派生クラスで実装されると、この Attribute の一意の識別子を取得します。

(継承元 Attribute)

メソッド

Equals(Object)

このインスタンスが、指定されたオブジェクトと等価であるかどうかを示す値を返します。

(継承元 Attribute)
GetHashCode()

このインスタンスのハッシュ コードを返します。

(継承元 Attribute)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
IsDefaultAttribute()

派生クラスでオーバーライドされるとき、このインスタンスの値が派生クラスの既定値であるかどうかを示します。

(継承元 Attribute)
Match(Object)

派生クラス内でオーバーライドされたときに、指定したオブジェクトとこのインスタンスが等しいかどうかを示す値を返します。

(継承元 Attribute)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

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

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

一連の名前を対応する一連のディスパッチ識別子に割り当てます。

(継承元 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

オブジェクトの型情報を取得します。この情報はインターフェイスの型情報の取得に使用できます。

(継承元 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

オブジェクトが提供する型情報インターフェイスの数 (0 または 1) を取得します。

(継承元 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

オブジェクトによって公開されたプロパティおよびメソッドへのアクセスを提供します。

(継承元 Attribute)

適用対象

こちらもご覧ください