c# - C# 中 StringToInt 函数的最佳解决方案

标签 c#

上周在一次求职面试中,我被要求在白板上做一个 StringToInt/Int.parse 函数,但表现不是很好,但我想出了某种解决方案。后来回到家后,我在 Visual Studio 中做了一个,我想知道是否有比下面我的更好的解决方案。

除了检查字符串是否只包含数字外,不再费心处理任何错误。

        private int StrToInt(string tmpString)
    {
        int tmpResult = 0;

        System.Text.Encoding ascii = System.Text.Encoding.ASCII;
        byte[] tmpByte = ascii.GetBytes(tmpString);

        for (int i = 0; i <= tmpString.Length-1; i++)
        {
            // Check whatever the Character is an valid digit
            if (tmpByte[i] > 47 && tmpByte[i] <= 58)
                // Here I'm using the lenght-1 of the string to set the power and multiply this to the value
                tmpResult += (tmpByte[i] - 48) * ((int)Math.Pow(10, (tmpString.Length-i)-1));
            else
                throw new Exception("Non valid character in string");

        } 

        return tmpResult;
    }

最佳答案

我会采取逆向方法。

public int? ToInt(this string mightBeInt)
{
    int convertedInt;
    if (int.TryParse(mightBeInt, out convertedInt))
    {
        return convertedInt;
    }
    return null;
}

在被告知这不是问题的重点之后,我认为该问题测试的是 C 编码技能,而不是 C#。我进一步争辩说,将字符串视为字符数组在 .NET 中是一个非常糟糕的习惯,因为字符串是 unicode,并且在任何可能全局化的应用程序中,对字符表示的任何假设都会让你很快陷入困境或以后。此外,该框架已经提供了一种转换方法,它比开发人员匆忙扔掉的任何东西都更加高效和可靠。重新发明框架功能总是一个坏主意。

然后我会指出,通过编写扩展方法,我已经为字符串类创建了一个非常有用的扩展,我将在生产代码中实际使用它。

如果这个争论让我失去了工作,我可能无论如何都不想在那里工作。

编辑:正如一些人所指出的,我错过了 TryParse 中的“out”关键字。固定。

关于c# - C# 中 StringToInt 函数的最佳解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2943499/

相关文章:

c# - 使用 C# 解压缩上传到 Azure Web Apps 的文件

c# - VS 代码中的 "Cannot find or open the PDB file"

c# - List.Any() 在预期为 false 时返回 true

c# - .net 如何明智地使用 .dll?

c# - Windows 操作系统之间的 SQL 连接字符串是否不同?

c# - 使用对 Msvm_ResourceAllocationSettingData 的 WMI 查询查找特定的 SCSI Controller

c# - 如何在 Azure 辅助角色中生成安全随机数?

c# - 与 MySql (ADO.NET) 的数据连接 - ConsoleApplication C# vs2015

c# - IEnumerable 上的 FirstOrDefault 具有不可为空的内容

c# - 单元测试未显示测试结果