![](/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.