ConfigurationConverterBase 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
配置转换器类型的基类。
public ref class ConfigurationConverterBase abstract : System::ComponentModel::TypeConverter
public abstract class ConfigurationConverterBase : System.ComponentModel.TypeConverter
type ConfigurationConverterBase = class
inherit TypeConverter
Public MustInherit Class ConfigurationConverterBase
Inherits TypeConverter
- 继承
- 派生
示例
下面的代码示例演示如何从 ConfigurationConverterBase 类派生以创建自定义 TimeSpan 转换器类型。 此外,这些示例还演示了如何在自定义节中使用此类型。
下面的代码示例演示如何从 ConfigurationConverterBase 类创建自定义TimeSpan转换器类型。
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
public sealed class CustomTimeSpanMinutesConverter :
ConfigurationConverterBase
{
internal bool ValidateType(object value,
Type expected)
{
bool result;
if ((value != null) &&
(value.GetType() != expected))
result = false;
else
result = true;
return result;
}
public override bool CanConvertTo(
ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override bool CanConvertFrom(
ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override object ConvertTo(
ITypeDescriptorContext ctx, CultureInfo ci,
object value, Type type)
{
ValidateType(value, typeof(TimeSpan));
long data = (long)(((TimeSpan)value).TotalMinutes);
return data.ToString(CultureInfo.InvariantCulture);
}
public override object ConvertFrom(
ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
long min = long.Parse((string)data,
CultureInfo.InvariantCulture);
return TimeSpan.FromMinutes((double)min);
}
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Globalization
Imports System.ComponentModel
NotInheritable Public Class CustomTimeSpanMinutesConverter
Inherits ConfigurationConverterBase
Friend Function ValidateType(ByVal value As Object, _
ByVal expected As Type) As Boolean
Dim result As Boolean
If Not (value Is Nothing) _
AndAlso value.ToString() <> expected.ToString() Then
result = False
Else
result = True
End If
Return result
End Function 'ValidateType
Public Overrides Function CanConvertTo( _
ByVal ctx As ITypeDescriptorContext, _
ByVal type As Type) As Boolean
Return (type.ToString() = GetType(String).ToString())
End Function 'CanConvertTo
Public Overrides Function CanConvertFrom( _
ByVal ctx As ITypeDescriptorContext, _
ByVal type As Type) As Boolean
Return (type.ToString() = GetType(String).ToString())
End Function 'CanConvertFrom
Public Overrides Function ConvertTo( _
ByVal ctx As ITypeDescriptorContext, _
ByVal ci As CultureInfo, ByVal value As Object, _
ByVal type As Type) As Object
ValidateType(value, GetType(TimeSpan))
Dim data As Long = _
Fix(CType(value, TimeSpan).TotalMinutes)
Return data.ToString(CultureInfo.InvariantCulture)
End Function 'ConvertTo
Public Overrides Function ConvertFrom( _
ByVal ctx As ITypeDescriptorContext, _
ByVal ci As CultureInfo, ByVal data As Object) As Object
Dim min As Long = _
Long.Parse(CStr(data), CultureInfo.InvariantCulture)
Return TimeSpan.FromMinutes(System.Convert.ToDouble(min))
End Function 'ConvertFrom
End Class
下面的代码示例演示如何定义使用上一个自定义转换器的自定义 TimeSpan 节。
// Define a custom section.
public sealed class CustomSection :
ConfigurationSection
{
public CustomSection()
{
}
[ConfigurationProperty("fileName", DefaultValue=" default.txt ")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
public String FileName
{
get
{
return (String)this["fileName"];
}
set
{
this["fileName"] = value;
}
}
[ConfigurationProperty("maxIdleTime")]
[TypeConverter(typeof(CustomizedTimeSpanMinutesConverter))]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
[ConfigurationProperty("timeDelay",
DefaultValue = "infinite")]
[TypeConverter(typeof(InfiniteTimeSpanConverter))]
public TimeSpan TimeDelay
{
get
{
return (TimeSpan)this["timeDelay"];
}
set
{
this["timeDelay"] = value;
}
}
[ConfigurationProperty("cdStr",
DefaultValue = "str0, str1",
IsRequired = true)]
[TypeConverter(typeof(
CommaDelimitedStringCollectionConverter))]
public StringCollection CdStr
{
get
{
return (StringCollection)this["cdStr"];
}
set
{
this["cdStr"] = value;
}
}
public enum Permissions
{
FullControl = 0,
Modify = 1,
ReadExecute = 2,
Read = 3,
Write = 4,
SpecialPermissions = 5
}
[ConfigurationProperty("permission", DefaultValue = Permissions.Read)]
public Permissions Permission
{
get
{
return (Permissions)this["permission"];
}
set
{
this["permission"] = value;
}
}
[ConfigurationProperty("maxUsers", DefaultValue="infinite")]
[TypeConverter(typeof(InfiniteIntConverter))]
public int MaxUsers
{
get
{
return (int)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
}
}
}
' Define a custom section.
NotInheritable Public Class CustomSection
Inherits ConfigurationSection
Public Sub New()
End Sub
<ConfigurationProperty("fileName", _
DefaultValue:=" default.txt "), _
TypeConverter(GetType(WhiteSpaceTrimStringConverter))> _
Public Property FileName() As String
Get
Return CStr(Me("fileName"))
End Get
Set(ByVal value As String)
Me("fileName") = value
End Set
End Property
<ConfigurationProperty("maxIdleTime"), _
TypeConverter(GetType(CustomizedTimeSpanMinutesConverter))> _
Public Property MaxIdleTime() As TimeSpan
Get
Return CType(Me("maxIdleTime"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("maxIdleTime") = value
End Set
End Property
<ConfigurationProperty("timeDelay", _
DefaultValue:="infinite"), _
TypeConverter(GetType(InfiniteTimeSpanConverter))> _
Public Property TimeDelay() As TimeSpan
Get
Return CType(Me("timeDelay"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("timeDelay") = Value
End Set
End Property
<ConfigurationProperty("cdStr", _
DefaultValue:="str0, str1", _
IsRequired:=True), _
TypeConverter(GetType(CommaDelimitedStringCollectionConverter))> _
Public Property CdStr() As StringCollection
Get
Return CType(Me("cdStr"), StringCollection)
End Get
Set(ByVal value As StringCollection)
Me("cdStr") = value
End Set
End Property
Public Enum Permissions
FullControl = 0
Modify = 1
ReadExecute = 2
Read = 3
Write = 4
SpecialPermissions = 5
End Enum 'Permissions
<ConfigurationProperty("permission", _
DefaultValue:=Permissions.Read)> _
Public Property Permission() As Permissions
Get
Return CType(Me("permission"), Permissions)
End Get
Set(ByVal value As Permissions)
Me("permission") = Value
End Set
End Property
<ConfigurationProperty("maxUsers", _
DefaultValue:="infinite"), _
TypeConverter(GetType(InfiniteIntConverter))> _
Public Property MaxUsers() As Integer
Get
Return Fix(Me("maxUsers"))
End Get
Set(ByVal value As Integer)
Me("maxUsers") = Value
End Set
End Property
End Class
下面的代码示例演示如何使用上一个自定义部分创建和修改配置文件。
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
namespace Samples.AspNet
{
// Define a custom section.
public sealed class CustomSection :
ConfigurationSection
{
public CustomSection()
{ }
[ConfigurationProperty("fileName", DefaultValue = "default.txt",
IsRequired = true, IsKey = false)]
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
MinLength = 1, MaxLength = 60)]
public string FileName
{
get
{
return (string)this["fileName"];
}
set
{
this["fileName"] = value;
}
}
[ConfigurationProperty("maxIdleTime")]
[TypeConverter(typeof(TsMinutesConverter))]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
}
public sealed class TsMinutesConverter :
ConfigurationConverterBase
{
internal bool ValidateType(object value, Type expected)
{
bool result;
if ((value != null) &&
(value.GetType() != expected))
result = false;
else
result = true;
return result;
}
public override bool CanConvertTo(
ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override bool CanConvertFrom(
ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override object ConvertTo(
ITypeDescriptorContext ctx, CultureInfo ci,
object value, Type type)
{
ValidateType(value, typeof(TimeSpan));
long data = (long)(((TimeSpan)value).TotalMinutes);
return data.ToString(CultureInfo.InvariantCulture);
}
public override object ConvertFrom(
ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
long min = long.Parse((string)data,
CultureInfo.InvariantCulture);
return TimeSpan.FromMinutes((double)min);
}
}
class UsingConfigutationConverterBase
{
// Create a custom section.
static void CreateSection()
{
try
{
CustomSection customSection;
// Get the current configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Create the section entry
// in the <configSections> and the
// related target section in <configuration>.
if (config.Sections["CustomSection"] == null)
{
customSection = new CustomSection();
config.Sections.Add("CustomSection", customSection);
customSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
// Change custom section and write it to disk.
static void SerializeCustomSection()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
CustomSection customSection =
config.Sections.Get("CustomSection")
as CustomSection;
TimeSpan ts =
new TimeSpan(1, 30, 30);
customSection.MaxIdleTime = ts;
config.Save();
string maxIdleTime =
customSection.MaxIdleTime.ToString();
Console.WriteLine("New max idle time: {0}",
maxIdleTime);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
// Read custom section from disk.
static void DeserializeCustomSection()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
CustomSection customSection =
config.Sections.Get("CustomSection")
as CustomSection;
TimeSpan maxIdleTime =
customSection.MaxIdleTime;
Console.WriteLine("Max idle time: {0}",
maxIdleTime.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void Main(string[] args)
{
CreateSection();
SerializeCustomSection();
DeserializeCustomSection();
}
}
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Globalization
Imports System.ComponentModel
' Define a custom section.
NotInheritable Public Class CustomSection
Inherits ConfigurationSection
Public Sub New()
End Sub
<ConfigurationProperty("fileName", _
DefaultValue:="default.txt", _
IsRequired:=True, IsKey:=False), _
StringValidator(InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
MinLength:=1, MaxLength:=60)> _
Public Property FileName() As String
Get
Return CStr(Me("fileName"))
End Get
Set(ByVal value As String)
Me("fileName") = value
End Set
End Property
<ConfigurationProperty("maxIdleTime"), _
TypeConverter(GetType(TsMinutesConverter))> _
Public Property MaxIdleTime() As TimeSpan
Get
Return CType(Me("maxIdleTime"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("maxIdleTime") = Value
End Set
End Property
End Class
NotInheritable Public Class TsMinutesConverter
Inherits ConfigurationConverterBase
Friend Function ValidateType(value As Object, expected As Type) As Boolean
Dim result As Boolean
If Not (value Is Nothing) _
AndAlso (value.GetType().Equals(expected) <> True) Then
result = False
Else
result = True
End If
Return result
End Function 'ValidateType
Public Overrides Function CanConvertTo( _
ByVal ctx As ITypeDescriptorContext, _
ByVal type As Type) As Boolean
Return type.Equals(GetType(String))
End Function 'CanConvertTo
Public Overrides Function CanConvertFrom( _
ByVal ctx As ITypeDescriptorContext, _
ByVal type As Type) As Boolean
Return type.Equals(GetType(String))
End Function 'CanConvertFrom
Public Overrides Function ConvertTo( _
ByVal ctx As ITypeDescriptorContext, ByVal ci As CultureInfo, _
ByVal value As Object, ByVal type As Type) As Object
ValidateType(value, GetType(TimeSpan))
Dim data As Long = _
Fix(CType(value, TimeSpan).TotalMinutes)
Return data.ToString(CultureInfo.InvariantCulture)
End Function 'ConvertTo
Public Overrides Function ConvertFrom( _
ByVal ctx As ITypeDescriptorContext, ByVal ci As CultureInfo, _
ByVal data As Object) As Object
Dim min As Long = _
Long.Parse(CStr(data), _
CultureInfo.InvariantCulture)
Return TimeSpan.FromMinutes( _
System.Convert.ToDouble(min))
End Function 'ConvertFrom
End Class
Class UsingConfigutationConverterBase
' Create a custom section.
Shared Sub CreateSection()
Try
Dim customSection As CustomSection
' Get the current configuration file.
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
' Create the section entry
' in the <configSections> and the
' related target section in <configuration>.
If config.Sections("CustomSection") Is Nothing Then
customSection = New CustomSection()
config.Sections.Add("CustomSection", customSection)
customSection.SectionInformation.ForceSave = True
config.Save(ConfigurationSaveMode.Full)
End If
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
' Change custom section and write it to disk.
Shared Sub SerializeCustomSection()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim customSection _
As CustomSection = _
config.Sections.Get("CustomSection")
Dim ts As New TimeSpan(1, 30, 30)
customSection.MaxIdleTime = ts
config.Save()
Dim maxIdleTime As String = _
customSection.MaxIdleTime.ToString()
Console.WriteLine( _
"New max idle time: {0}", maxIdleTime)
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub
' Read custom section from disk.
Shared Sub DeserializeCustomSection()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim customSection _
As CustomSection = _
config.Sections.Get("CustomSection")
Dim maxIdleTime As TimeSpan = _
customSection.MaxIdleTime
Console.WriteLine( _
"Max idle time: {0}", maxIdleTime.ToString())
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub
Public Overloads Shared Sub Main(ByVal args() As String)
CreateSection()
SerializeCustomSection()
DeserializeCustomSection()
End Sub
End Class
下面是上一个示例使用的配置摘录。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="CustomSection"
type="Samples.AspNet.CustomSection,
ConfigurationConverters,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null"
allowDefinition="Everywhere"
allowExeDefinition="MachineToApplication"
restartOnExternalChanges="true" />
</configSections>
<CustomSection fileName="default.txt" maxIdleTime="90" />
</configuration>
注解
ConfigurationConverterBase是转换器配置类型的基类。 这些类型用于将配置文件中找到的字符串与相关的强类型属性进行转换。
构造函数
ConfigurationConverterBase() |
初始化 ConfigurationConverterBase 类的新实例。 |