这个示例是用 C# 编写的,但我希望可以同样轻松地应用于其他示例。
我最近发现以下似乎工作得很好:
int i = Int32.TryParse(SomeString, out i) ? i : -1;
不知何故,似乎变量 i
在它出现在 TryParse
中时在技术上不应该是可访问的。或者我假设 int i
有效地声明了变量是否正确,即使还没有语句结束?
最佳答案
int i
声明变量,并在 out
参数中使用它来初始化它。由于必须在结果之前评估谓词,因此 i
在使用之前既已声明又已初始化。 (out
参数必须在返回前赋值,所以无论如何肯定是初始化了。)
也就是说,我的一些同事会因为风格原因而大发雷霆。 :-)
编辑:在调查了这一切的变化之后,我将提出几个可能的替代辅助方法。静态类的命名充当此处辅助方法的意图文档。
internal static class TryConvert
{
/// <summary>
/// Returns the integer result of parsing a string, or null.
/// </summary>
internal static int? ToNullableInt32(string toParse)
{
int result;
if (Int32.TryParse(toParse, out result)) return result;
return null;
}
/// <summary>
/// Returns the integer result of parsing a string,
/// or the supplied failure value if the parse fails.
/// </summary>
internal static int ToInt32(string toParse, int toReturnOnFailure)
{
// The nullable-result method sets up for a coalesce operator.
return ToNullableInt32(toParse) ?? toReturnOnFailure;
}
}
internal static class CallingCode
{
internal static void Example(string someString)
{
// Name your poison. :-)
int i = TryConvert.ToInt32(someString, -1);
int j = TryConvert.ToNullableInt32(someString) ?? -1;
// This avoids the issue of a sentinel value.
int? k = TryConvert.ToNullableInt32(someString);
if (k.HasValue)
{
// do something
}
}
}
关于c# - 声明变量并使用 TryParse 在同一行对其进行初始化有任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566205/