ConfigurationPropertyAttribute ConfigurationPropertyAttribute ConfigurationPropertyAttribute ConfigurationPropertyAttribute Class

定義

.NET Framework が構成プロパティをインスタンス化するように、宣言によって指示します。Declaratively instructs the .NET Framework to instantiate a configuration property. このクラスは継承できません。This class cannot be inherited.

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

次の例は、 ConfigurationSection ConfigurationPropertyAttribute属性を使用してカスタムオブジェクトのプロパティを定義する方法を示しています。The following example shows how to define the properties of a custom ConfigurationSection object using the ConfigurationPropertyAttribute attribute.

この例には、2つのクラスが含まれています。The example contains two classes. カスタムUrlsSectionクラスは、 ConfigurationPropertyAttributeを使用して独自のプロパティを定義します。The UrlsSection custom class uses the ConfigurationPropertyAttribute to define its own properties. クラスUsingConfigurationPropertyAttributeは、 UrlsSectionを使用して、アプリケーション構成ファイルのカスタムセクションの読み取りと書き込みを行います。The UsingConfigurationPropertyAttribute class uses the UrlsSection to read and write the custom section in the application configuration file.

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

前の例で定義されているカスタムセクションを含む構成ファイルの抜粋を次に示します。The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

<?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 Framework がインスタンス化され、装飾パラメーターの値を使用してプロパティが初期化されます。You use the ConfigurationPropertyAttribute to decorate a configuration property, which will instruct the .NET Framework to instantiate and to initialize the property using the value of the decorating parameter.

注意

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

  1. カスタム構成要素のプロパティのインスタンスを作成する方法を .NET Framework 指示する型。The types instructing the .NET Framework how to instantiate the custom configuration-element properties. 次のような種類があります。These types include:

  2. カスタム構成要素のプロパティを検証する方法を .NET Framework に指示する型。The types instructing the .NET Framework how to validate the custom configuration-element properties. 次のような種類があります。These types include:

コンストラクター

ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String)

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

プロパティ

DefaultValue DefaultValue DefaultValue DefaultValue

装飾されたプロパティの既定値を取得または設定します。Gets or sets the default value for the decorated property.

IsDefaultCollection IsDefaultCollection IsDefaultCollection IsDefaultCollection

これが、装飾された構成プロパティに対する既定プロパティのコレクションかどうかを示す値を取得または設定します。Gets or sets a value indicating whether this is the default property collection for the decorated configuration property.

IsKey IsKey IsKey IsKey

これが、装飾された要素のプロパティに対する主要プロパティかどうかを示す値を取得または設定します。Gets or sets a value indicating whether this is a key property for the decorated element property.

IsRequired IsRequired IsRequired IsRequired

装飾された要素のプロパティが必要かどうかを示す値を取得または設定します。Gets or sets a value indicating whether the decorated element property is required.

Name Name Name Name

装飾された構成要素のプロパティの名前を取得します。Gets the name of the decorated configuration-element property.

Options Options Options Options

装飾された構成要素のプロパティの ConfigurationPropertyOptions を取得または設定します。Gets or sets the ConfigurationPropertyOptions for the decorated configuration-element property.

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)

適用対象

こちらもご覧ください