C# 数值文本互转工具类
using System;
using System.ComponentModel;
namespace System
{
public static class SimpleConverter
{
/// <summary>
/// [ String | 数值字符串 ] -> [ ValueType | 数值 ]
/// </summary>
/// <typeparam name="T">[ ValueType | 数值类型 ]</typeparam>
/// <param name="value">[ String | 数值字符串 ]</param>
/// <exception cref="NotSupportedException"></exception>
/// <returns></returns>
public static T ToNumber<T>(string value) where T : struct
{
var cast = TypeDescriptor.GetConverter(typeof(T));
if (cast != null)
{
return (T) cast.ConvertFromInvariantString(value);
}
return default(T);
}
/// <summary>
/// [ String | 数值字符串 ] -> [ ValueType | 数值 ]
/// </summary>
/// <typeparam name="T">[ ValueType | 数值类型 ]</typeparam>
/// <param name="value">[ String | 数值字符串 ]</param>
/// <param name="def">[ DefaultValue | 默认数值 ]</param>
/// <returns></returns>
public static T ToNumber<T>(string value, T def) where T : struct
{
try
{
var answer = ToNumber<T>(value);
return Equals(answer, default(T)) ? def : answer;
}
catch (NotSupportedException)
{
return def;
}
}
/// <summary>
/// [ ValueType | 数值 ] -> [ String | 数值字符串 ]
/// </summary>
/// <typeparam name="T">[ ValueType | 数值类型 ]</typeparam>
/// <param name="value">[ ValueType | 数值 ]</param>
/// <exception cref="NotSupportedException"></exception>
/// <returns></returns>
public static string ToString<T>(T value) where T : struct
{
var cast = TypeDescriptor.GetConverter(typeof(T));
if (cast != null)
{
return cast.ConvertToInvariantString(value);
}
return Convert.ToString(value);
}
/// <summary>
/// [ ValueType | 数值 ] -> [ String | 数值字符串 ]
/// </summary>
/// <typeparam name="T">[ ValueType | 数值类型 ]</typeparam>
/// <param name="value">[ ValueType | 数值 ]</param>
/// <param name="def">[ DefaultString | 默认数值字符串 ]</param>
/// <returns></returns>
public static string ToString<T>(T value, string def) where T : struct
{
try
{
var answer = ToString<T>(value);
return String.IsNullOrEmpty(answer) ? def : answer;
}
catch (NotSupportedException)
{
return def;
}
}
}
}