优雅的TryParse [英] Elegant TryParse
本文介绍了优雅的TryParse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我觉得我每次使用的TryParse
,这导致有些丑陋的代码的时间。主要是我使用这种方式:
I feel that every time I use TryParse
that it results in somewhat ugly code. Mainly I am using it this way:
int value;
if (!int.TryParse(someStringValue, out value)
value = 0;
有没有分析所有的基本数据类型,要具体一些更优雅的解决方案是有办法做到在一行中的故障安全解析?通过故障安全我想设置的默认值,如果解析无一例外失败。
Is there some more elegant solution for parsing all basic data types, to be specific is there a way to do fail safe parsing in one line? By fail safe I assume setting default value if parsing fails without exception.
顺便说一句,这是一个情况下,即使解析失败,只使用默认值,我必须做一些动作。
By the way, this is for cases where I must do some action even if parsing fails, just using the default value.
推荐答案
怎么样直接扩展方法?
public class Extensions
{
public static int? TryParse(string this Source)
{
if(int.tryparse ....
}
}
用法:
v = "234".TryParse() ?? 0
这篇关于优雅的TryParse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文