0
A
回答
3
public class GenericsManager
{
public static T ChangeType<T>(object data)
{
T value = default(T);
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
value = (T)Convert.ChangeType(data, Nullable.GetUnderlyingType(typeof(T)));
}
else
{
if (data != null)
{
value = (T)Convert.ChangeType(data, typeof(T));
}
}
return value;
}
}
没有大量有用的在这里,但我想你可以利用这一点,并验证了结果不等于该类型的默认值。
但是,tryparse要好得多,并且要达到您所要做的。
3
1
您可以使用正则表达式来确定它们可能是什么类型。虽然这将是一个有点麻烦,如果你需要一个int和一个字节之间者区分如果该值小于255
0
您可以在TryParse和正则表达式之间混用。这不是一个漂亮的代码,但速度很快,并且您可以在任何地方使用该方法。
有关于布尔类型的问题。 或可以表示布尔值,但也可以是类型字节。我解析了true和false文本值,但是关于您的业务规则,您应该决定什么是最适合您的。
public static Type getTypeFromString(String s)
{
if (s.Length == 1)
if (new Regex(@"[^0-9]").IsMatch(s)) return Type.GetType("System.Char");
else
return Type.GetType("System.Byte", true, true);
if (new Regex(@"^(\+|-)?\d+$").IsMatch(s))
{
Decimal d;
if (Decimal.TryParse(s, out d))
{
if (d <= Byte.MaxValue && d >= Byte.MinValue) return Type.GetType("System.Byte", true, true);
if (d <= UInt16.MaxValue && d >= UInt16.MinValue) return Type.GetType("System.UInt16", true, true);
if (d <= UInt32.MaxValue && d >= UInt32.MinValue) return Type.GetType("System.UInt32", true, true);
if (d <= UInt64.MaxValue && d >= UInt64.MinValue) return Type.GetType("System.UInt64", true, true);
if (d <= Decimal.MaxValue && d >= Decimal.MinValue) return Type.GetType("System.Decimal", true, true);
}
}
if (new Regex(@"^(\+|-)?\d+[" + NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator + @"]\d*$").IsMatch(s))
{
Double d;
if (Double.TryParse(s, out d))
{
if (d <= Single.MaxValue && d >= Single.MinValue) return Type.GetType("System.Single", true, true);
if (d <= Double.MaxValue && d >= Double.MinValue) return Type.GetType("System.Double", true, true);
}
}
if(s.Equals("true",StringComparison.InvariantCultureIgnoreCase) || s.Equals("false",StringComparison.InvariantCultureIgnoreCase))
return Type.GetType("System.Boolean", true, true);
DateTime dateTime;
if(DateTime.TryParse(s, out dateTime))
return Type.GetType("System.DateTime", true, true);
return Type.GetType("System.String", true, true);
}
相关问题
- 1. 如何将数据类型转换为可读的字符串
- 2. PHP - 是否可以从字符串的值转换为类型?
- 3. 是否可以将字符串转换为List数据类型?
- 4. Javascript:可以将字符串转换为/转换为类型常量吗?
- 5. 如何将特定字符串转换为特定的int
- 6. cocoa:如何将整数类型转换为字符串类型?
- 7. 使用转换将字符串转换为自定义类型
- 8. 字符串转换类型类类型
- 9. 将字符串转换为字符串的泛型类型
- 10. 将字符串转换为'Date'类型
- 11. 将字符串值转换为类型
- 12. 类型转换为字符串在C++
- 13. 将字符串转换为类型UTCTime
- 14. 将字符串类型转换为int
- 15. 将字符串转换为类型“LuaFunction”
- 16. 将MYSQL_ROW类型转换为字符串
- 17. Python-如何验证字符串是否以特定字符串结尾?
- 18. 如何将类型转换为可以在vb .net中编译的字符串?
- 19. 如何将字符串转换为运行时确定的可空类型?
- 20. 如何将字符串转换为泛型类型对象
- 21. (字符串)字符类型转换
- 22. TextEncoding可以转换为字符串吗?
- 23. 转换/字符串添加到特定类型
- 24. 如何将字符串转换为Typescript中的字符串文字类型?
- 25. 将字符串转换为字符串类型的片段
- 26. 无法将类型'字符串'隐式转换为'字符串'
- 27. 字符串转换为美孚(字符串类型)
- 28. C宏将字符串转换为pascal字符串类型
- 29. 类型字符串()的值不能转换为字符串
- 30. 如何将字符串转换为任何类型的对象?
是否有一个特别的原因,您不想使用TryParse?这是最简单,最强大的方式,也可能是最快的方法之一。 – 2009-06-24 10:11:00