ConfigurationPropertyAttribute Klass
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Deklarativt instruerar .NET att instansiera en konfigurationsegenskap. Det går inte att ärva den här klassen.
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
- Arv
- Attribut
Exempel
I följande exempel visas hur du definierar egenskaperna för ett anpassat ConfigurationSection objekt med hjälp av attributet ConfigurationPropertyAttribute .
Exemplet innehåller två klasser. Den UrlsSection anpassade klassen använder ConfigurationPropertyAttribute för att definiera sina egna egenskaper. Klassen UsingConfigurationPropertyAttribute använder UrlsSection för att läsa och skriva det anpassade avsnittet i programkonfigurationsfilen.
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
Följande är ett utdrag av konfigurationsfilen som innehåller det anpassade avsnittet enligt definitionen i föregående exempel.
<?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>
Kommentarer
Du använder ConfigurationPropertyAttribute för att dekorera en konfigurationsegenskap, vilket instruerar .NET att instansiera och initiera egenskapen med hjälp av värdet för dekoreringsparametern.
Note
Det enklaste sättet att skapa ett anpassat konfigurationselement är att använda den tillskrivna (deklarativa) modellen. Du deklarerar anpassade offentliga egenskaper och dekorerar dem med attributet ConfigurationPropertyAttribute . För varje egenskap som har markerats med det här attributet använder .NET reflektion för att läsa dekoreringsparametrarna och skapa en relaterad ConfigurationProperty-instans. Du kan också använda den programmatiska modellen, i vilket fall det är ditt ansvar att deklarera anpassade offentliga egenskaper och returnera deras samling.
Konfigurationssystemet .NET innehåller attributtyper som du kan använda när du skapar anpassade konfigurationselement. Det finns två typer av attributtyper:
Typerna som instruerar .NET hur du instansierar de anpassade egenskaperna för konfigurationselement. Dessa typer omfattar:
De typer som instruerar .NET hur du verifierar egenskaperna för anpassade konfigurationselement. Dessa typer omfattar:
Konstruktorer
| Name | Description |
|---|---|
| ConfigurationPropertyAttribute(String) |
Initierar en ny instans av ConfigurationPropertyAttribute klassen. |
Egenskaper
| Name | Description |
|---|---|
| DefaultValue |
Hämtar eller anger standardvärdet för den dekorerade egenskapen. |
| IsDefaultCollection |
Hämtar eller anger ett värde som anger om det här är standardegenskapssamlingen för den dekorerade konfigurationsegenskapen. |
| IsKey |
Hämtar eller anger ett värde som anger om det här är en nyckelegenskap för den dekorerade elementegenskapen. |
| IsRequired |
Hämtar eller anger ett värde som anger om den dekorerade elementegenskapen krävs. |
| Name |
Hämtar namnet på den dekorerade egenskapen configuration-element. |
| Options |
Hämtar eller anger ConfigurationPropertyOptions för den dekorerade egenskapen configuration-element. |
| TypeId |
När den implementeras i en härledd klass hämtar du en unik identifierare för den här Attribute. (Ärvd från Attribute) |
Metoder
| Name | Description |
|---|---|
| Equals(Object) |
Returnerar ett värde som anger om den här instansen är lika med ett angivet objekt. (Ärvd från Attribute) |
| GetHashCode() |
Returnerar hash-koden för den här instansen. (Ärvd från Attribute) |
| GetType() |
Hämtar den aktuella instansen Type . (Ärvd från Object) |
| IsDefaultAttribute() |
När den åsidosättas i en härledd klass anger du om värdet för den här instansen är standardvärdet för den härledda klassen. (Ärvd från Attribute) |
| Match(Object) |
När den åsidosätts i en härledd klass returneras ett värde som anger om den här instansen är lika med ett angivet objekt. (Ärvd från Attribute) |
| MemberwiseClone() |
Skapar en ytlig kopia av den aktuella Object. (Ärvd från Object) |
| ToString() |
Returnerar en sträng som representerar det aktuella objektet. (Ärvd från Object) |
Explicita gränssnittsimplementeringar
| Name | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mappar en uppsättning namn till en motsvarande uppsättning av sändningsidentifierare. (Ärvd från Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Hämtar typinformationen för ett objekt, som kan användas för att hämta typinformationen för ett gränssnitt. (Ärvd från Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Hämtar antalet typinformationsgränssnitt som ett objekt tillhandahåller (antingen 0 eller 1). (Ärvd från Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Ger åtkomst till egenskaper och metoder som exponeras av ett objekt. (Ärvd från Attribute) |