在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)));
}
對我來說這是解決方案之一......但我不downvoter) – demo
我會說這是downvoted,因爲它只是一個黑客,而不是像其他答案的強大的解決方案。 – DavidG