C#中TryParse()的通用包装器

我正在使用以下方法提供对各种Type类的TryParse()方法快速内联访问.基本上我希望能够解析来自Web服务的字符串(如果可能),否则返回认值.
private Int64 Int64Parse(string value) {
    Int64 result;
    if (!Int64.TryParse(value,out result)) { return default(Int64); }
    return result;
}

private DateTime DateTimeParse(string value) {
    DateTime result;
    if (!DateTime.TryParse(value,out result)) { return default(DateTime); }
    return result;
}

private Decimal DecimalParse(string value) {
    Decimal result;
    if (!Decimal.TryParse(value,out result)) { return default(Decimal); }
    return result;
}

这些是非常重复的,对我来说,可能有一种方法可以将它们包装成单个通用方法.

我坚持以下但不确定如何继续或如何搜索如何继续.

private T ParseString<T>(string value) {
    T result;
    if (!T.TryParse(value,out result)) { return default(T); }
    return result;
}

任何帮助,将不胜感激.
谢谢.

== ==编辑
添加一些上下文.这是为了收听来自特定信用卡结算公司的回发的听众.我没有在此步骤进行验证,因为这是在稍后的业务规则步骤中完成的.例如,我不在乎bank_batch_number是作为int,string还是冻干的啮齿动物进入;如果我不能干净地记录我不使用的字段,我不会停止异常.我关心ext_product_id存在于我们的数据库中,并且在消息中具有与currency_amount_settled相匹配的价格;如果该测试失败,则交易被暂停,将记录警告,我们的CS员工和我自己将收到警报.

下面提到的文化事物是圣人的建议.

解决方法

为什么不使用简单的扩展方法

Jon Skeet关于仅使用各种TryParse方法认结果的答案是好的.不过,扩展方法仍然有一个很好的方面.如果你这么做很多,你可以在一行代码而不是三行代码中完成相同的调用代码(加上可选择指定显式认值).

– 编辑 – 我确实意识到,在我原来的答案中,我基本上只提供了一种略微不同的方式来做同样的事情,作者已经在做了.我今天早些时候抓到了这个,当我真正忙碌时,认为委托和自定义解析器的东西看起来可能有点多,然后在没有花时间完全理解问题的情况下找出答案.抱歉.

如何使用(重载)扩展方法和反射?参见https://stackoverflow.com/a/4740544/618649

警告Emptor:我的例子没有说明你试图转换没有TryParse方法的类型. getmethod调用应该有一些异常处理,依此类推.

/* The examples generates this output when run:

0
432123
-1
1/1/0001 12:00:00 AM
1/1/1970 12:00:00 AM
1/30/2013 12:00:00 PM
-1
12342.3233443

*/


class Program
    {
    static void Main ( string[] args )
        {
        Debug.WriteLine( "blah".Parse<Int64>() );
        Debug.WriteLine( "432123".Parse<long>() );
        Debug.WriteLine( "123904810293841209384".Parse<long>( -1 ) );

        Debug.WriteLine( "this is not a DateTime value".Parse<DateTime>() );
        Debug.WriteLine( "this is not a DateTime value".Parse<DateTime>( "jan 1,1970 0:00:00".Convert<DateTime>() ) );
        Debug.WriteLine( "2013/01/30 12:00:00".Parse<DateTime>() );

        Debug.WriteLine( "this is not a decimal value".Parse<decimal>( -1 ) );
        Debug.WriteLine( "12342.3233443".Parse<decimal>() );
        }
    }

static public class Extensions
    {
    static private Dictionary<Type,MethodInfo> s_methods = new Dictionary<Type,MethodInfo>();

    static public T Parse<T> ( this string value ) where T : struct
        {
        return value.Parse<T>( default( T ) );
        }

    static public T Parse<T> ( this string value,T defaultValue ) where T : struct
        {
        // *EDITED* to cache the Reflection lookup--NOT thread safe
        MethodInfo m = null;
        if ( s_methods.ContainsKey( typeof( T ) ) )
            {
            m = s_methods[ typeof( T ) ];
            }
        else
            {
            m = typeof( T ).getmethod(
                 "TryParse",BindingFlags.Public | BindingFlags.Static,Type.DefaultBinder,new[] { typeof( string ),typeof( T ).MakeByRefType() },null
                 );
            s_methods.Add( typeof( T ),m );
            }

        var args = new object[] { value,null };
        if( (bool)m.Invoke( null,args ))
            {
            return (T) args[ 1 ];
            }
        return defaultValue;
        }
    }

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么