using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace UniFramework.Utility
{
public static class StringConvert
{
///
/// 正则表达式
///
private static readonly Regex REGEX = new Regex(@"\{[-+]?[0-9]+\.?[0-9]*\}", RegexOptions.IgnoreCase);
///
/// 字符串转换为BOOL
///
public static bool StringToBool(string str)
{
int value = (int)Convert.ChangeType(str, typeof(int));
return value > 0;
}
///
/// 字符串转换为数值
///
public static T StringToValue(string str)
{
return (T)Convert.ChangeType(str, typeof(T));
}
///
/// 字符串转换为数值列表
///
/// 分隔符
public static List StringToValueList(string str, char separator)
{
List result = new List();
if (!String.IsNullOrEmpty(str))
{
string[] splits = str.Split(separator);
foreach (string split in splits)
{
if (!String.IsNullOrEmpty(split))
{
result.Add((T)Convert.ChangeType(split, typeof(T)));
}
}
}
return result;
}
///
/// 字符串转为字符串列表
///
public static List StringToStringList(string str, char separator)
{
List result = new List();
if (!String.IsNullOrEmpty(str))
{
string[] splits = str.Split(separator);
foreach (string split in splits)
{
if (!String.IsNullOrEmpty(split))
{
result.Add(split);
}
}
}
return result;
}
///
/// 转换为枚举
/// 枚举索引转换为枚举类型
///
public static T IndexToEnum(string index) where T : IConvertible
{
int enumIndex = (int)Convert.ChangeType(index, typeof(int));
return IndexToEnum(enumIndex);
}
///
/// 转换为枚举
/// 枚举索引转换为枚举类型
///
public static T IndexToEnum(int index) where T : IConvertible
{
if (Enum.IsDefined(typeof(T), index) == false)
{
throw new ArgumentException($"Enum {typeof(T)} is not defined index {index}");
}
return (T)Enum.ToObject(typeof(T), index);
}
///
/// 转换为枚举
/// 枚举名称转换为枚举类型
///
public static T NameToEnum(string name)
{
if (Enum.IsDefined(typeof(T), name) == false)
{
throw new ArgumentException($"Enum {typeof(T)} is not defined name {name}");
}
return (T)Enum.Parse(typeof(T), name);
}
///
/// 字符串转换为参数列表
///
public static List StringToParams(string str)
{
List result = new List();
MatchCollection matches = REGEX.Matches(str);
for (int i = 0; i < matches.Count; i++)
{
string value = matches[i].Value.Trim('{', '}');
result.Add(StringToValue(value));
}
return result;
}
}
}