2017-09-01 118 views
3

在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))); 
} 

回答

2

您可以添加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

對我來說這是解決方案之一......但我不downvoter) – demo

+0

我會說這是downvoted,因爲它只是一個黑客,而不是像其他答案的強大的解決方案。 – DavidG