关于 .NET 源码中 Convert.ToString (Int16, Int32) 的实现方法,求指点。

今天用到 Convert.ToString (Int16, Int32) 转换进制,很好奇 .NET Framework 中是如何实现的,就查了 .NET 源码,我使用的 .NET 源码版本是 dotnet_v4.6.2_RS1,在 ndp 中 Convert.ToString (Int16, Int32) 方法的定义如下:

        // Convert the byte value to a string in base fromBase
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static String ToString (byte value, int toBase) {
            if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
            }
            Contract.EndContractBlock();
            return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1);
        }

        // Convert the Int16 value to a string in base fromBase
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static String ToString (short value, int toBase) {
            if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
            }
            Contract.EndContractBlock();
            return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2);
        }

        // Convert the Int32 value to a string in base toBase
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static String ToString (int value, int toBase) {
            if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
            }
            Contract.EndContractBlock();
            return ParseNumbers.IntToString(value, toBase, -1, ' ', 0);
        }

        // Convert the Int64 value to a string in base toBase
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static String ToString (long value, int toBase) {
            if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
            }
            Contract.EndContractBlock();
            return ParseNumbers.LongToString(value, toBase, -1, ' ', 0);
        }

ParseNumbers 是一个内部类,在该类下 IntToString 的实现是这样的:

        [System.Security.SecurityCritical]  // auto-generated
        [ResourceExposure(ResourceScope.None)]
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        public extern static String IntToString(int l, int radix, int width, char paddingChar, int flags);

该方法使用了 extern 关键字,应该是调用了外部实现,但是具体调用的是哪里找不到,求大神们指点。

阅读 5.1k
2 个回答

MethodImplAttribute(MethodImplOptions.InternalCall) 说明了其实现位于 CLR 内部。在 .NET Core 之前微软的 CLR 好像是闭源的,所以基本上看不到其实现代码。但是从 .NET Core 开始,微软全面拥抱开源,其所谓 CoreCLR 也不例外,我从 CoreCLR 的 1.0.0 的源代码里找到了 IntToString 的 C++ 实现, 目前最新的 .NET Core 2.0+ (CoreCLR 2.0+)里已经改为 C# 实现.

看看特性里是不有定义

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进