C# ??结合? : question

标签 c# ternary-operator conditional-operator

我正在为一个项目构建一个 XML 反序列化器,我经常遇到这种类型的代码情况:

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

关于C# ??结合? : question,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526555/

相关文章:

c# - 具有五个数字级别的分层大纲 - 如何插入兄弟或子行并调整现有记录?

c# - 如何获取不在另一个列表中的列表元素C#

php - 三元运算符左结合性

jquery - 在 Chrome : conditional statement fails on jquery/ajax result

python - Tensorflow CIFAR-10 教程中的 bool 表达式

c++ - 条件运算符可以返回引用吗?

c# - 随机双数的多次迭代往往会变小

c# - 删除字典中的所有条目 c# WPF

三元运算符里面的Java Ternary Operator,如何求值?

python - 这个叫什么 : myVar = value1 or value2