1

我一直面临的问题之一是 .NET Framework 类库的实现。

我知道一些方法的原始实现:

例如 :

MessageBox.Show("...");

据我所知,此方法必须使用 P/Invoke 来调用 Win32 API。

但像这样:

System.Convert.ToInt32(mystr);

我实际上不知道它是如何工作的,因为在纯 C# 中不可能在 int 和 string 之间进行转换。(不使用该方法你能做完全相同的事情吗?实际上我不知道)。

最后,如果您知道答案,请特别为我澄清这些概念,特别是第二个示例。

4

4 回答 4

6

你能不使用那种方法做同样的事情吗?其实没有。

你绝对可以。这是一种非常低效的方法——它不考虑溢出、无效输入或负数,但演示了一般原则。

int ParseStringToInt32(string text)
{
    int result = 0;
    foreach (char c in text)
    {
        result = result * 10 + (c - '0');
    }
    return result;
}

从根本上说,将字符串解析为Int32. 这只是查看每个字符,考虑其数值并进行一些算术运算的情况。

确实,有时值得手动执行 - 在 Noda Time 中,我们有自己的数字解析代码,允许解析有限​​数量的字符而无需获取子字符串。

于 2014-12-30T20:26:24.890 回答
5

Microsoft has made the BCL available online at: http://referencesource.microsoft.com

Calling Convert.ToInt32(string) will eventually call int.Parse, which in turn will eventually call the actual routine on an internal Number class here:

One of the basic routines listed there is as follows:

    [System.Security.SecuritySafeCritical]  // auto-generated
    private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {

        Int32 i = number.scale;
        if (i > Int32Precision || i < number.precision) {
            return false;
        }
        char * p = number.digits;
        Contract.Assert(p != null, "");
        Int32 n = 0;
        while (--i >= 0) {
            if ((UInt32)n > (0x7FFFFFFF / 10)) {
                return false;
            }
            n *= 10;
            if (*p != '\0') {
                n += (Int32)(*p++ - '0');
            }
        }
        if (number.sign) {
            n = -n;
            if (n > 0) {
                return false;
            }
        }
        else {
            if (n < 0) {
                return false;
            }
        }
        value = n;
        return true;
    }
于 2014-12-30T20:35:10.420 回答
1

Implementation of MessageBox.Show is here.

Implementation of Convert.ToString is here.

于 2014-12-30T20:30:10.510 回答
1

试试这个:它不是微软的实现,因为它不是开源的。但它应该给你一个想法

https://github.com/mono/mono/blob/master/mcs/class/Managed.Windows.Forms/System.Windows.Forms/MessageBox.cs

于 2014-12-30T20:26:12.093 回答