详见以下示例
public class Program
{
public static void Main(string[] args)
{
var source = new Dictionary<string, string>
{
["point"] = "(123,456)"
};
//MemoryConfigurationProvider使用内存中集合作为配置键值对。若要激活内存中集合配置,请在
//ConfigurationBuilder的实例上调用AddInMemoryCollection扩展方法。可以使用
//IEnumerable<KeyValuePair<String,String>> 初始化配置提供程序。构建主机时调用
//ConfigureAppConfiguration以指定应用程序的配置:
var root = new ConfigurationBuilder().AddInMemoryCollection(source).Build();
//在这里调用TypeConverter
var point = root.GetValue<Point>("point");
Console.WriteLine(point.X);
Console.WriteLine(point.Y);
Console.ReadKey();
}
}
//注册了一个类型为PointTypeConverter的TypeConverter,
//PointTypeConvert通过实现的ConvertForm方法将坐标的字符串表达式转换为一个Point对象
[TypeConverter(typeof(PointTypeConverter))]
public class Point
{
public double X { get; set; }
public double Y { get; set; }
}
public class PointTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string);
public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string[] split = value.ToString().Split(',');
double x = double.Parse(split[0].Trim().TrimStart('('));
double y = double.Parse(split[1].Trim().TrimEnd(')'));
return new Point {X=x,Y=y };
}
}