首页 > 解决方案 > 如何从我自己的系统命名空间(包含我的自定义 Int32)中访问 dotnet 的 System.Int32 类型?

问题描述

从我的自定义顶级System命名空间(我还定义了 struct Int32)中,我无法访问 dotnet 的标准System.Int32类型。我自己Systme.Int32隐藏了 dotnet 的System.Int32. 我尝试使用global::完全限定System.Int32名称以获取 dotnet 的标准类型,但它仍然引用我自己的类型。我找不到解决办法。在https://stackoverflow.com/a/3830520/423632阅读 Eric Lippert 对相关问题的 11 岁回答表明我需要为此编写自己的编译器。但这不应该是不可能的。

以下代码无法编译,给出了引用 Main 方法中第一条语句的错误:
错误 CS0029:无法将类型 'int' 隐式转换为 'System.Int32'

// DOES NOT COMPILE ! 

using System; 

namespace System
{


    struct Int32
    {

        public override string ToString()
        {

            return "My own Int32 lol";


        }
    }

    class Program
    {
        static int Main(string[] args)
        {
            global::System.Int32 x = 5; // error CS0029 
            Console.WriteLine(x);
            return 0;
        }

    }

}

标签: c#.net.net-core

解决方案


我发现的一种方法是使用外部别名:

extern alias MSCorLib;
namespace System
{
    struct Int32
    {
        public override string ToString()
        {
            return "My own Int32 lol";
        }
    }
    class Program
    {
        static int Main(string[] args)
        {
            MSCorLib::System.Int32 x = 5;
            Console.WriteLine(x);
            return 0;
        }

    }
}

如果您使用以下-reference选项编译它:

csc Program.cs -reference:MSCorLib=mscorlib.dll

然后它将按预期打印 5 。

具体来说Int32,您也可以只使用int

int x = 5;

当然,这也适用于double, float,short等。


推荐阅读