【问题标题】:How to access dotnet's System.Int32 type from within my own System namespace (containing my custom Int32)?如何从我自己的系统命名空间(包含我的自定义 Int32)中访问 dotnet 的 System.Int32 类型?
【发布时间】:2021-11-06 08:12:15
【问题描述】:

在我的自定义顶级 System 命名空间(我还定义了结构 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;
        }

    }

}

【问题讨论】:

  • 只适合在家玩的人。为什么要这样做?
  • @TheGeneral 在复习 C# 的命名空间规则时,我的脑海中突然出现了这个问题。不会立即将其用于任何事情,但考虑到如此丰富而强大的平台(如果确实不可能的话),这是一种奇怪的无能。

标签: c# .net .net-core


【解决方案1】:

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

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;

当然,这也适用于doublefloatshort

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多