是的你可以。我曾经遇到过您的问题并为 Textbox 控件实现了扩展。它是一种通用方法,可以转换十进制、整数、任何值类型。
public static T? GetTextOrNullStruct<T>(this TextBox txt, GlobalSist.Common.Utils.ParserCondition? parserCondition, bool throwOnValidation)
where T : struct, IComparable<T>
{
return GlobalSist.Common.Utils.Parsers.ConvertStruct<T>(
GetTextOrNull(txt), parserCondition, throwOnValidation);
}
public static T? ConvertStruct<T>(IConvertible value, ParserCondition? parserCondition, bool throwOnValidation)
where T : struct, IComparable<T>
{
try
{
if ((value == null) ||
(value is string && string.IsNullOrEmpty((string)value)))
{
if (throwOnValidation)
throw new ArgumentNullException("value");
else
return null;
}
return Parsers.Convert<T>(value, parserCondition, true);
}
catch (ArgumentOutOfRangeException)
{
if (throwOnValidation)
throw;
else
return null;
}
}
这是转换为字符串的方法
public static T Convert<T>(IConvertible value, ParserCondition? parserCondition, bool throwOnValidation)
where T : IComparable<T>
{
T convertedValue;
try
{
convertedValue = (T)value.ToType(typeof(T), null);
}
catch (Exception ex)
{
if (throwOnValidation)
throw new ArgumentOutOfRangeException(ex.Message, ex);
else
return default(T);
}
return ValidateParserCondition<T>(convertedValue, parserCondition, throwOnValidation);
}
编辑:忘记粘贴最后调用的方法
private static T ValidateParserCondition<T>(T value, ParserCondition? parserCondition, bool throwOnValidation)
where T : IComparable<T>
{
if (parserCondition == null)
return value;
else
{
int comparingToZero = value.CompareTo(default(T));
switch (parserCondition.Value)
{
case ParserCondition.GreaterOrEqualToZero:
if (comparingToZero >= 0)
return value;
break;
case ParserCondition.GreaterThanZero:
if (comparingToZero > 0)
return value;
break;
case ParserCondition.LessOrEqualToZero:
if (comparingToZero <= 0)
return value;
break;
case ParserCondition.LessThanZero:
if (comparingToZero < 0)
return value;
break;
default:
throw new NotImplementedException("ParserCondition at ValidateParserCondition");
}
if (throwOnValidation)
throw new ArgumentOutOfRangeException(
string.Format("value {0} not in accordance with ParserCondition {1}",
value, parserCondition.Value.ToString()));
else
return default(T);
}
}
枚举声明是:
public enum ParserCondition
{
/// <summary>
/// >=0
/// </summary>
GreaterOrEqualToZero,
/// <summary>
/// >0
/// </summary>
GreaterThanZero,
/// <summary>
/// <=0
/// </summary>
LessOrEqualToZero,
/// <summary>
/// <0
/// </summary>
LessThanZero,
}