54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using System;
|
|
using System.ComponentModel;
|
|
using System.Globalization;
|
|
using JD.Kernel.StaticHelpers;
|
|
|
|
namespace JD.Maths.Utils
|
|
{
|
|
/// <summary>
|
|
/// Converts math structures from string.
|
|
/// </summary>
|
|
public abstract class MathConverterBase : TypeConverter
|
|
{
|
|
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
|
|
{
|
|
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
|
|
}
|
|
|
|
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
|
|
{
|
|
string text = value as string;
|
|
if (text == null)
|
|
{
|
|
return base.ConvertFrom(context, culture, value);
|
|
}
|
|
|
|
int valuesCount = ValuesCount;
|
|
float[] values = new float[valuesCount];
|
|
|
|
int currentIndex = 0;
|
|
for (int i = 0; i < valuesCount; ++i)
|
|
{
|
|
int nextIndex = text.IndexOf(',', currentIndex);
|
|
if (nextIndex < 0)
|
|
{
|
|
Throw.InvalidArgumentIf(i != valuesCount - 1, "String does not have enough parts.", "value");
|
|
values[i] = float.Parse(text.Substring(currentIndex), culture.NumberFormat);
|
|
currentIndex = -1;
|
|
}
|
|
else
|
|
{
|
|
values[i] = float.Parse(text.Substring(currentIndex, nextIndex - currentIndex), culture.NumberFormat);
|
|
currentIndex = nextIndex + 1;
|
|
}
|
|
}
|
|
|
|
Throw.InvalidArgumentIf(currentIndex != -1, "String does not have enough parts.", "value");
|
|
return CreateStruct(values);
|
|
}
|
|
|
|
protected abstract object CreateStruct(float[] parsedValue);
|
|
|
|
protected abstract int ValuesCount { get; }
|
|
}
|
|
}
|