10

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

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

当然可以为此使用 Typeonverters。但是,无效的转换会导致异常,我想摆脱它。

4

2 回答 2

16

TryParse您可以使用反射动态调用该方法。这样,如果转换失败,您将不会收到耗时的异常。

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

    //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;
}
于 2012-07-14T07:35:41.283 回答
2

你可以这样写:

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);

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

于 2012-07-14T07:33:21.290 回答