gpt4 book ai didi

C# ??结合? : question

转载 作者:行者123 更新时间:2023-11-30 13:29:33 28 4
gpt4 key购买 nike

我正在为一个项目构建一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com