![](/img/trans.png)
[英]Take string value from appsetting.json and set it to JSON Key in c#
[英]Parse appsetting value from string to array of strings
在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)));
}
您可以添加TypeConverter
以在string
和string[]
之間進行轉換:
[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
是您在代碼中使用的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.