将字符串中的appsetting值解析为字符串数组

5
在 app.config 文件中,我有一个自定义部分和自定义元素。
<BOBConfigurationGroup>
    <BOBConfigurationSection>
        <emails test="test1@test.com, test2@test.com"></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(); }
    }
}

但是当我运行我的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)));
 }
2个回答

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

0

考虑一种类似的方法:

    [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
对我来说,这是其中一种解决方案...但我不是那个投反对票的人) - demo
我认为这个回答被踩是因为它只是一个hack,而不像其他答案那样是一个强大的解决方案。 - DavidG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接