所以我有一個配置節/ ConfigurationElementCollection中有這樣的配置:如何將TypeConverters與ConfigurationSection一起使用?
<mimeFormats>
<add mimeFormat="text/html" />
</mimeFormats>
這裏是我如何處理mimeFormats:
public class MimeFormatElement: ConfigurationElement
{
#region Constructors
/// <summary>
/// Predefines the valid properties and prepares
/// the property collection.
/// </summary>
static MimeFormatElement()
{
// Predefine properties here
_mimeFormat = new ConfigurationProperty(
"mimeFormat",
typeof(MimeFormat),
"*/*",
ConfigurationPropertyOptions.IsRequired
);
}
private static ConfigurationProperty _mimeFormat;
private static ConfigurationPropertyCollection _properties;
[ConfigurationProperty("mimeFormat", IsRequired = true)]
public MimeFormat MimeFormat
{
get { return (MimeFormat)base[_mimeFormat]; }
}
}
public class MimeFormat
{
public string Format
{
get
{
return Type + "/" + SubType;
}
}
public string Type;
public string SubType;
public MimeFormat(string mimeFormatStr)
{
var parts = mimeFormatStr.Split('/');
if (parts.Length != 2)
{
throw new Exception("Invalid MimeFormat");
}
Type = parts[0];
SubType = parts[1];
}
}
很顯然,我需要一個類型轉換器,它實際東西(而不是這個空殼):
public class MimeFormatConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
throw new NotImplementedException();
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
throw new NotImplementedException();
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
throw new NotImplementedException();
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
如何建立一個類型轉換器,將允許類型的便利着想從/到字符串的rsion?我試過使用MSDN的例子,但我不斷收到錯誤信息:
TypeConverter無法從System.String轉換。
本質上,它是如何設置的,以便它可以與任何ConfigurationSection試圖做的事情一起工作?
您不需要手動獲取'TypeConverter'。刪除'TypeDescriptor.GetConverter ...'。正如你所做的那樣,將TypeConverter分配給屬性或鍵入本身就足夠了。 – 2011-05-09 18:51:48