c# - 如何从我自己的系统命名空间(包含我的自定义 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;
}
}
}
解决方案
我发现的一种方法是使用外部别名:
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
等。
推荐阅读
- oracle - 来自元数据的 Oracle 列数据类型
- android - 'view' 容器在 Android 的 XML 中做了什么
- vagrant - 在 Vagrant libvirt 提供程序中为管理网络设置静态 IP
- python - pandas 最大数据返回元数据样式?
- opencv - /usr/bin/ld: 找不到 -lvtkRenderingOpenGL
- amazon-web-services - 如何通过 S3 静态网站托管在 API 网关上使用自定义域
- python - 获取 ttk.Combobox 中选定项目的索引
- kubernetes - EKS Kubernetes 无法在集群范围内的 API 组“”中列出资源“命名空间”
- c++ - 如何使用 gMock 创建 Mock 对象?
- bash - 如何使用 CTRL+C 杀死 bash 脚本