代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace Utils
{
public static class StringUtils
{
public static readonly string[] TypesNames = new[]
{
"Boolean",
"Byte",
"SByte",
"Int16",
"Int32",
"Int64",
"UInt16",
"UInt32",
"UInt64",
"Single",
"Double",
"Decimal",
"Char",
"String",
"DateTime"
};
private static readonly Dictionary<string, Type> Types = new Dictionary<string, Type>(StringComparer.Ordinal)
{
{"Boolean", typeof(bool)},
{"Byte", typeof(byte)},
{"SByte", typeof(sbyte)},
{"Int16", typeof(short)},
{"Int32", typeof(int)},
{"Int64", typeof(long)},
{"UInt16", typeof(ushort)},
{"UInt32", typeof(uint)},
{"UInt64", typeof(ulong)},
{"Single", typeof(float)},
{"Double", typeof(double)},
{"Decimal", typeof(decimal)},
{"Char", typeof(char)},
{"String", typeof(string)},
{"DateTime", typeof(DateTime)}
};
private static readonly Dictionary<string, object> InitValues = new Dictionary<string, object>(StringComparer.Ordinal)
{
{"Boolean", new bool()},
{"Byte", new byte()},
{"SByte", new sbyte()},
{"Int16", new short()},
{"Int32", new int()},
{"Int64", new long()},
{"UInt16", new ushort()},
{"UInt32", new uint()},
{"UInt64", new ulong()},
{"Single", new float()},
{"Double", new double()},
{"Decimal", new decimal()},
{"Char", new char()},
{"String", ""},
{"DateTime", new DateTime()}
};
public static bool isTypeSupported(Type aType)
{
if (aType.IsArray)
{
if(aType.GetArrayRank() == 1)
{
return Types.ContainsKey(aType.GetElementType()?.Name);
}
else
{
return false;
}
}
else
{
return Types.ContainsKey(aType.Name);
}
}
public static bool isTypeSupported(string aType)
{
return Types.ContainsKey(aType);
}
public static Type parseType(string aType)
{
if(string.IsNullOrWhiteSpace(aType))
{
throw new ArgumentException("Type name is empty. ");
}
if(aType.StartsWith("System."))
{
aType = aType.Substring(7);
}
if (Types.ContainsKey(aType) == false)
{
throw new ArgumentException("Type '" aType "' is not supported. ");
}
return Types[aType];
}
public static Type getTypeByIndex(int aIndex)
{
return Types[TypesNames[aIndex]];
}
public static int getIndexByType(Type aType)
{
for(int i = 0; i < TypesNames.Length; i )
{
if (TypesNames[i].Equals(aType.Name, StringComparison.Ordinal)) return i;
}
throw new ArgumentException("Type '" aType.Name "' is not supported. ");
}
public static object getInitValue(string aType, bool aArray = false, int aLength = 0)
{
if (string.IsNullOrWhiteSpace(aType))
{
throw new ArgumentException("Type name is empty. ");
}
if (aType.StartsWith("System."))
{
aType = aType.Substring(7);
}
if (InitValues.ContainsKey(aType) == false)
{
throw new ArgumentException("Type '" aType "' is not supported. ");
}
if (aLength < 0)
{
throw new ArgumentException("Length is less than zero. ");
}
if (aArray)
{
return Array.CreateInstance(Types[aType], aLength);
}
else
{
if (aLength > 1)
{
throw new ArgumentException("Length is wrong. ");
}
return InitValues[aType];
}
}
public static object getInitValue(Type aType, bool aArray = false, int aLength = 0)
{
return getInitValue(aType.Name, aArray, aLength);
}
public const string DTwMsFormat = "yyyy.MM.dd HH:mm:ss.fff";
public const string DTFormat = "yyyy.MM.dd HH:mm:ss";
public static float toSingle(this string aValue)
{
int lLastC = aValue.LastIndexOf(',');
if (lLastC > aValue.LastIndexOf('.'))
{
aValue = aValue.Substring(0, lLastC).Replace(".", "") "." aValue.Substring(lLastC 1);
}
return float.Parse(aValue.Replace(" ", ""), CultureInfo.InvariantCulture);
}
public static double toDouble(string aValue)
{
int lLastC = aValue.LastIndexOf(',');
if (lLastC > aValue.LastIndexOf('.'))
{
aValue = aValue.Substring(0, lLastC).Replace(".", "") "." aValue.Substring(lLastC 1);
}
return double.Parse(aValue.Replace(" ", ""), CultureInfo.InvariantCulture);
}
public static decimal toDecimal(string aValue)
{
int lLastC = aValue.LastIndexOf(',');
if (lLastC > aValue.LastIndexOf('.'))
{
aValue = aValue.Substring(0, lLastC).Replace(".", "") "." aValue.Substring(lLastC 1);
}
return decimal.Parse(aValue.Replace(" ", ""), CultureInfo.InvariantCulture);
}
public static object StringToObject(Type aType, string aString)
{
try
{
if (aType == typeof(string))
{
return aString;
}
else if (aType == typeof(float))
{
return toSingle(aString);
}
else if (aType == typeof(double))
{
return toDouble(aString);
}
else if (aType == typeof(decimal))
{
return toDecimal(aString);
}
else if (aType == typeof(DateTime))
{
return DateTime.ParseExact(aString, DTwMsFormat, CultureInfo.InvariantCulture);
}
else if (aType == typeof(Color))
{
KnownColor lColor;
if (Enum.TryParse(aString, out lColor))
{
return Color.FromKnownColor(lColor);
}
else
{
return Color.FromArgb(Convert.ToInt32(aString, 16));
}
}
else if (aType == typeof(Font))
{
string[] lParam = aString.Split(';');
return new Font(lParam[0], (float)StringToObject(typeof(float), lParam[1]), (FontStyle)Enum.Parse(typeof(FontStyle), lParam[2]));
}
else
{
object lValue;
try
{
lValue = aType.InvokeMember("Parse", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { aString });
}
catch (TargetInvocationException lExc)
{
throw lExc.InnerException;
}
return lValue;
}
}
catch (Exception lExc)
{
throw new ArgumentException("String '" aString "' conversion error to object of type '" aType.FullName "'. " lExc.Message, lExc);
}
}
public const char ArrayStringSeparator = 'u0001';
public static object StringToArray(Type aType, string aString)
{
Array lArray;
Type lElementType;
if (aType.IsArray)
{
lElementType = aType.GetElementType();
}
else
{
lElementType = aType;
}
try
{
if (aString.StartsWith("[") == false) throw new ArgumentException("Wrong format. ");
int lIndex = aString.IndexOf(']');
if(lIndex == -1) throw new ArgumentException("Wrong format. ");
if(aString[lIndex 1] != '{') throw new ArgumentException("Wrong format. ");
if (aString.EndsWith("}") == false ) throw new ArgumentException("Wrong format. ");
int lLength = (int)StringToObject(typeof(int), aString.Substring(1, lIndex - 1));
string[] lValues = aString.Substring(lIndex 2, aString.Length - lIndex - 3).Split(ArrayStringSeparator);
if(lValues.Length == 1 && string.IsNullOrWhiteSpace(lValues[0]) && lLength == 0)
{
return Array.CreateInstance(lElementType, 0);
}
if (lValues.Length != lLength) throw new ArgumentException("Wrong length. ");
lArray = Array.CreateInstance(lElementType, lLength);
for(int i = 0; i < lLength; i )
{
lArray.SetValue(StringToObject(lElementType, lValues[i]), i);
}
return lArray;
}
catch (Exception lExc)
{
try
{
lArray = Array.CreateInstance(lElementType, 1);
lArray.SetValue(StringToObject(lElementType, aString), 0);
return lArray;
}
catch {}
throw new ArgumentException("String '" aString "' conversion error to array of type '"
aType.FullName "'. " lExc.Message, lExc);
}
}
public static string ArrayToString(Array aArray, string aFormat = "")
{
if (aArray.Rank == 1)
{
int lLen = aArray.GetLength(0);
StringBuilder lStrBld = new StringBuilder("[" lLen.ToString() "]{");
for (int i = 0; i < lLen; i )
{
lStrBld.Append(ObjectToString(aArray.GetValue(i), aFormat));
if ((i 1) != lLen)
{
lStrBld.Append(ArrayStringSeparator);
}
}
lStrBld.Append("}");
return lStrBld.ToString();
}
else
{
return aArray.ToString();
}
}
public static string ObjectToString(object aObject, string aFormat = "")
{
switch (aObject)
{
case null:
return "null";
case float f:
return f.ToString(aFormat, CultureInfo.InvariantCulture);
case double d:
return d.ToString(aFormat, CultureInfo.InvariantCulture);
case decimal o:
return o.ToString(aFormat, CultureInfo.InvariantCulture);
case DateTime time when string.IsNullOrWhiteSpace(aFormat):
return time.ToString(DTwMsFormat);
case DateTime time:
return time.ToString(aFormat);
case Color lColor when lColor.IsNamedColor:
return lColor.Name;
case Color lColor:
return lColor.ToArgb().ToString("X8");
case Font lFont:
return lFont.FontFamily.Name ";" ObjectToString(lFont.Size) ";" lFont.Style.ToString();
case Array array:
return ArrayToString(array, aFormat);
default:
return aObject.ToString();
}
}
public static string DoubleToString(double aValue, int aRound)
{
if (aRound == -1)
{
return ObjectToString(aValue);
}
else
{
string lValue = ObjectToString(Math.Round(aValue, aRound, MidpointRounding.AwayFromZero));
if (aRound > 0 && lValue.Contains("E") == false)
{
int lSeparator = lValue.LastIndexOf(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, StringComparison.Ordinal);
int lAddZero;
if (lSeparator == -1)
{
lValue = lValue CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator;
lAddZero = lValue.Length aRound;
}
else
{
lAddZero = lSeparator CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator.Length aRound;
}
lValue = lValue.PadRight(lAddZero, '0');
}
return lValue;
}
}
public static int getLineCount(string aText)
{
return aText.Split(new[] {Environment.NewLine}, StringSplitOptions.None).Length;
}
public static int getLineNumber(string aText, int aIndex)
{
return aText.Substring(0, aIndex).Split(new[] {Environment.NewLine}, StringSplitOptions.None).Length;
}
public static int getIndex(string[] aArray, string aValue)
{
for (int i = 0; i < aArray.Length; i )
{
if (aValue.Equals(aArray[i], StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
}
}