本文介绍了如何动态调用的TryParse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法的TryParse
动态调用?有些类型的:
Is there a way to call TryParse
dynamically? Some kind of:
public static bool TryParse<T>(string toConvert, out T result)
当然,人们可以使用Typeonverters这一点。然而,一个无效的转换将导致异常,我想摆脱这一点。
Of course one can use Typeonverters for this. However, an invalid conversion will result in an exception and I want to get rid of this.
推荐答案
您可以动态地使用反射调用的TryParse
方法。这样你就不会得到一个时间,如果转换失败消费异常。
You could call the TryParse
method dynamically using Reflection. This way you won't get a time consuming Exception if the conversion fails.
//Try Parse using Reflection
public static bool TryConvertValue<T>(string stringValue, out T convertedValue)
{
var targetType = typeof(T);
if (targetType == typeof(string))
{
convertedValue = (T)Convert.ChangeType(stringValue, typeof(T));
return true;
}
var nullableType = targetType.IsGenericType &&
targetType.GetGenericTypeDefinition() == typeof (Nullable<>);
if (nullableType)
{
if (string.IsNullOrEmpty(stringValue))
{
convertedValue = default(T);
return true;
}
targetType = new NullableConverter(targetType).UnderlyingType;
}
Type[] argTypes = { typeof(string), targetType.MakeByRefType() };
var tryParseMethodInfo = targetType.GetMethod("TryParse", argTypes);
if (tryParseMethodInfo == null)
{
convertedValue = default(T);
return false;
}
object[] args = { stringValue, null };
var successfulParse = (bool)tryParseMethodInfo.Invoke(null, args);
if (!successfulParse)
{
convertedValue = default(T);
return false;
}
convertedValue = (T)args[1];
return true;
}
这篇关于如何动态调用的TryParse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!