如何动态调用TryParse?

时间:2012-07-14 07:21:45

标签: c# .net type-conversion

有没有办法动态调用TryParse?某种:

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

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

2 个答案:

答案 0 :(得分:11)

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

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

    //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;
}

答案 1 :(得分: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);

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