dem*_*emo 5 c# arrays string parsing config
在 app.config 中,我有带有自定义元素的自定义部分。
<BOBConfigurationGroup>
<BOBConfigurationSection>
<emails test="test1@test.com, test2@test.com"></emails>
</BOBConfigurationSection>
</BOBConfigurationGroup>
Run Code Online (Sandbox Code Playgroud)
对于电子邮件元素,我有自定义类型:
public class EmailAddressConfigurationElement : ConfigurationElement, IEmailConfigurationElement
{
[ConfigurationProperty("test")]
public string[] Test
{
get { return base["test"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
set { base["test"] = value.JoinStrings(); }
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行我的 webApp 时,出现错误:
无法解析属性“test”的值。错误是:无法找到支持类型为“String[]”的属性“test”的字符串转换的转换器。
有没有办法在 getter 中拆分字符串?
我可以获取字符串值,然后在需要数组时“手动”拆分它,但在某些情况下我可以忘记它,所以最好从一开始就接收数组。
JoinStrings - 是我的自定义扩展方法
public static string JoinStrings(this IEnumerable<string> strings, string separator = ", ")
{
return string.Join(separator, strings.Where(s => !string.IsNullOrEmpty(s)));
}
Run Code Online (Sandbox Code Playgroud)
您可以添加 a在和TypeConverter之间进行转换:stringstring[]
[TypeConverter(typeof(StringArrayConverter))]
[ConfigurationProperty("test")]
public string[] Test
{
get { return (string[])base["test"]; }
set { base["test"] = value; }
}
public class StringArrayConverter: TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string[]);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ((string)value).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return value.JoinStrings();
}
}
Run Code Online (Sandbox Code Playgroud)