加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# ??结合?:问题

发布时间:2020-12-15 23:51:34 所属栏目:百科 来源:网络整理
导读:我正在为一个项目构建一个 XML Deserializer,我经常遇到这种类型的代码情况: var myVariable = ParseNDecimal(xml.Element("myElement")) == null ? 0 : ParseNDecimal(xml.Element("myElement")).Value; 有没有更好的方式来写这个陈述? 编辑:也许我应该
我正在为一个项目构建一个 XML Deserializer,我经常遇到这种类型的代码情况:

var myVariable = ParseNDecimal(xml.Element("myElement")) == null ? 
                 0 : ParseNDecimal(xml.Element("myElement")).Value;

有没有更好的方式来写这个陈述?

编辑:也许我应该澄清我的例子,因为我有一个帮助方法将字符串解析成十进制.

解决方法

您可以使用扩展方法:

public static T TryGetValue<T>( this XmlElement element ) {
    if ( null == element ) return default(T);
    return (T)element.Value;
}
...
...
var myVariable = xml.Element("myElement").TryGetValue<decimal>();

编辑:

“通用”解决方案:

static class Program {
    static void Main() {
        var xmlDecimal = new XElement( "decimal" );
        xmlDecimal.Value = ( 123.456m ).ToString();
        decimal valueOfDecimal_1 = xmlDecimal.ValueAs<decimal>( decimal.TryParse );
        bool valueOfBool_1 = xmlDecimal.ValueAs<bool>( bool.TryParse );

        var xmlBool = new XElement( "bool" );
        xmlBool.Value = true.ToString();
        decimal valueOfDecimal_2 = xmlBool.ValueAs<decimal>( decimal.TryParse );
        bool valueOfBool_2 = xmlBool.ValueAs<bool>( bool.TryParse );
    }
}

public static class StaticClass {
    public delegate bool TryParseDelegate<T>( string text,out T value );
    public static T ValueAs<T>( this XElement element,TryParseDelegate<T> parseDelegate ) {
        return ValueAs<T>( element,parseDelegate,default( T ) );
    }
    public static T ValueAs<T>( this XElement element,TryParseDelegate<T> parseDelegate,T defaultValue ) {
        if ( null == element ) { return defaultValue; }

        T result;
        bool ok = parseDelegate( element.Value,out result );
        if ( ok ) { return result; }

        return defaultValue;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读