有没有办法的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;
}