TryParse
動的に呼び出す方法はありますか?ある種の:
public static bool TryParse<T>(string toConvert, out T result)
もちろん、これにはTypeonvertersを使用できます。ただし、無効な変換は例外になり、これを取り除きたいと思います。
TryParse
動的に呼び出す方法はありますか?ある種の:
public static bool TryParse<T>(string toConvert, out T result)
もちろん、これにはTypeonvertersを使用できます。ただし、無効な変換は例外になり、これを取り除きたいと思います。
TryParse
Reflectionを使用してメソッドを動的に呼び出すことができます。このようにして、変換が失敗した場合に時間のかかる例外が発生することはありません。
このメソッドは、このメソッドのわずかに最適化されたバージョンです。
//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;
}
あなたはこのようなものを書くことができます:
public delegate bool TryParser<T>(string input, out T result);
public static bool TryParse<T>
(string toConvert, out T result, TryParser<T> 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<T>)Delegate.CreateDelegate
(typeof(TryParser<T>), method);
}
return tryParser(toConvert, out result);
}
そしてそれを次のように呼びます:
int result;
bool success = TryParse("123", out result);
あなたがそれを必要とするいくつかのシナリオがない限り、私は本当にこれをお勧めしません。