如何动态调用TryParse?

有没有办法动态调用TryParse ? 一些:

 public static bool TryParse(string toConvert, out T result) 

当然,人们可以使用Typeonverters。 但是,无效的转换会导致exception,我想摆脱这种情况。

您可以使用Reflection动态调用TryParse方法。 这样,如果转换失败,您将无法获得耗时的Exception。

此方法是此方法的略微优化版本。

  //Try Parse using Reflection public static bool TryConvertValue(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; } 

你可以写这样的东西:

 public delegate bool TryParser(string input, out T result); public static bool TryParse (string toConvert, out T result, TryParser tryParser = null) { if (toConvert == null) throw new ArgumentNullException("toConvert"); // This whole block is only if you really need // it to work in a truly dynamic way. You can additionally consider // memoizing the default try-parser on a per-type basis. if (tryParser == null) { var method = typeof(T).GetMethod ("TryParse", new[] { typeof(string), typeof(T).MakeByRefType() }); if (method == null) throw new InvalidOperationException("Type does not have a built in try-parser."); tryParser = (TryParser)Delegate.CreateDelegate (typeof(TryParser), method); } return tryParser(toConvert, out result); } 

然后称之为:

 int result; bool success = TryParse("123", out result); 

我真的不会推荐这个,除非你有一些需要它的场景。