所以我有一个配置如下的 ConfigurationSection/ConfigurationElementCollection:
<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];
}
}
显然我需要一个 TypeConverter 来实际做一些事情(而不是这个空壳):
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();
}
}
如何设置一个 TypeConverter 以允许从/到字符串的类型转换?我已尝试使用 MSDN 示例,但我不断收到错误消息:
TypeConverter cannot convert from System.String.
从本质上讲,如何设置它才能使其与 ConfigurationSection 试图做的任何事情一起工作?
最佳答案
您可以将 TypeConverterAttribute 放在属性上以告诉序列化程序如何处理它。
[TypeConverter(typeof(MimeFormatConverter))]
[ConfigurationProperty("mimeFormat", IsRequired = true)]
public MimeFormat MimeFormat
{
get { return (MimeFormat)base[_mimeFormat]; }
}
关于c# - 如何将 TypeConverter 与 ConfigurationSection 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5939854/