解析从字符串到字符串数组的appsetting值

问题描述:

在app.config中我使用自定义元素的自定义部分。解析从字符串到字符串数组的appsetting值

<BOBConfigurationGroup> 
    <BOBConfigurationSection> 
     <emails test="[email protected], [email protected]"></emails> 
    </BOBConfigurationSection> 
</BOBConfigurationGroup> 

的电子邮件元素我有自定义类型:

public class EmailAddressConfigurationElement : ConfigurationElement, IEmailConfigurationElement 
{ 
    [ConfigurationProperty("test")] 
    public string[] Test 
    { 
     get { return base["test"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } 
     set { base["test"] = value.JoinStrings(); } 
    } 
} 

但是当我运行我的Web应用程序,我得到错误:

属性“测试”的价值无法解析。错误是:无法找到一个转换器,该转换器支持对类型为'String []'的属性'test'进行字符串转换。

是否有任何解决方案来拆分getter中的字符串?

我可以获取字符串值,然后当我需要数组时,可以“手动”分割它,但是在某些情况下,我可以忘记它,所以从开始接收数组更好。


JoinStrings - 是我的自定义扩展方法

public static string JoinStrings(this IEnumerable<string> strings, string separator = ", ") 
{ 
    return string.Join(separator, strings.Where(s => !string.IsNullOrEmpty(s))); 
} 

您可以添加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(); 
    } 
} 

考虑类似的做法:

[ConfigurationProperty("test")] 
    public string Test 
    { 
     get { return (string) base["test"]; } 
     set { base["test"] = value; } 
    } 

    public string[] TestSplit 
    { 
     get { return Test.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } 
    } 

其中TestSplit是您在代码中使用的属性。

+1

对我来说这是解决方案之一......但我不downvoter) – demo

+0

我会说这是downvoted,因为它只是一个黑客,而不是像其他答案的强大的解决方案。 – DavidG