c# - byte.TryParse() 哪种方法更好

标签 c#

我只需要建议以确保哪种方法更好

1)

byte flag = 2; 
byte.TryParse(strFlag, out flag);

2)

byte flag; 
if (!byte.TryParse(strFlag, out flag)) 
{ 
    flag = 2; 
}

谢谢!!!

最佳答案

如果 TryParse 失败,我假设您想将 flag 设置为 2。

第一种方法是错误的。如果失败,它将用 0 覆盖您的值(因为这是 byte 类型的默认值)。您应该使用第二种解决方案。

关于c# - byte.TryParse() 哪种方法更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157839/

相关文章:

c# - 使用 c# 在 ASP.Net 中从 session 中检索 DateTime 和计算 TimeSpan 时出现问题。

c# - BitArray 改变范围内的位

c# - SQL Server 查询 : Get a List of Columns Which Don't Exist in Another Table's Field

c# - Owin最大并发请求数

c# - Linq 按 2 列(创建和修改)排序,以较大者为准

c# - 为什么我不能对字节执行 bool 逻辑?

c# - 使用 WPF 和 Caliburn.Micro 在一个 View 中添加多个 View

c# - 监视 WPF 中 Telerik ScheduleView 控件的属性更改

c# - 在 Webcontrols 上使用 “Using” block 有什么问题?

c# - EventTriggerBehavior Taped 未触发