gpt4 book ai didi

c# - 构造具有不同输出的 C# 代码,唯一的区别应该是 Nullable 与 int?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:34 25 4
gpt4 key购买 nike

作为我recently found out int?Nullable<int>并不总是可以互换的。 (当然,所有具有 Nullable 对应项的类型都是如此,而不仅仅是 int。)

我想知道的是:有没有一种方法可以构建有效的 C# 代码,您可以在其中替换 int?Nullable<int> (一些 出现,所以不是全部,但不一定只有一个)并得到一个仍然有效的 C# 代码,但具有不同的含义?

我不把例子算作解决方案,其中 int?Nullable<int>是字符串文字的一部分,所以这个简单的案例不是我要找的:

if ("int?".Contains("int?"))
Console.WriteLine("true");
else
Console.WriteLine("false");
// prints "true"

if ("int?".Contains("Nullable<int>"))
Console.WriteLine("true");
else
Console.WriteLine("false");
// prints "false"

这里还有一个更复杂的版本,它仍然使用字符串,但向您展示了编写代码的可能性非常大,只有这种差异导致不同的含义(不幸的是,只有一个版本是有效的 C#):

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerResults results = codeProvider.CompileAssemblyFromSource(new CompilerParameters(), "using System; class Foo { static void Main() { int a=1; var test = a is Nullable<byte> & true; } }");
Console.WriteLine(results.Errors.Count > 0 ? "false" : "true");
// prints "true"

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerResults results = codeProvider.CompileAssemblyFromSource(new CompilerParameters(), "using System; class Foo { static void Main() { int a=1; var test = a is byte? & true; } }");
Console.WriteLine(results.Errors.Count > 0 ? "false" : "true");
// prints "false"

(关于为什么一个编译而另一个不编译,我建议您查看此 questionanswer。)

所以我的问题是你能构建这样的代码吗?如果不是,那为什么不呢?

最佳答案

好吧,一个简单的例子就是声明一个名为 Nullable<T> 的本地类型的任何东西。 ; int将始终解析为 global::System.Int32 , 和 ? T? 上的后缀将始终解析为 global::System.Nullable<T> ,但是Nullable<T>手动编写的将使用常规规则解析 - 这意味着它可能不是您所期望的:

static void Main()
{
string s = (new Nullable<int>(123)).GetType().Assembly.FullName;
string t = (new int?(123)).GetType().Assembly.FullName;
}
struct Nullable<T> {public Nullable(T value){} }

关于c# - 构造具有不同输出的 C# 代码,唯一的区别应该是 Nullable<int> 与 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25524766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com