在「Deedy.Testing」中添加TypeConverter示例

This commit is contained in:
zengwenjie
2025-09-26 11:35:07 +08:00
parent e96e385f5b
commit 2d73f2de0c
2 changed files with 42 additions and 1 deletions

View File

@@ -157,7 +157,7 @@ namespace Deedy.Activity.Helpers
/// </summary>
/// <param name="geometryString">矢量图形的字符串表示形式</param>
/// <returns>如果解析成功则返回「Geometry」对象</returns>
public static Geometry? Help_ParseAsGeometry(this string geometryString) => TypeDescriptor.GetConverter(typeof(Geometry)).ConvertFromString(geometryString) as Geometry;
public static PathGeometry? Help_ParseAsPathGeometry(this string geometryString) => TypeDescriptor.GetConverter(typeof(PathGeometry)).ConvertFromString(geometryString) as PathGeometry;
/// <summary>
/// 以图形中心点为中心沿顺时针旋转指定角度再对一个矢量图形进行连续的「缩放」、「平移」到一个「Rectangle」
/// </summary>

View File

@@ -0,0 +1,41 @@

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
[TypeConverter(typeof(PointConverter))]
public struct Point
{
public double X { get; set; }
public double Y { get; set; }
}
public class PointConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
=> sourceType == typeof(string);
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
var str = value as string;
if (string.IsNullOrEmpty(str)) return null;
var parts = str.Split(',');
return new Point
{
X = double.Parse(parts[0]),
Y = double.Parse(parts[1])
};
}
public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType)
=> destinationType == typeof(string);
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (value == null) return "";
var point = (Point)value;
return $"{point.X},{point.Y}";
}
}