构造具有不同输出的c#代码,唯一的区别应该是Nullable<;int>;与内部

本文关键字:Nullable 内部 int lt gt 唯一 输出 代码 区别 | 更新日期: 2023-09-27 18:19:48

正如我最近发现的,int?Nullable<int>并不总是可互换的。(当然,这适用于所有具有Nullable对应项的类型,而不仅仅是int。)

我想知道的是:有没有一种方法可以构造有效的C#代码,用Nullable<int>替换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"

(关于为什么一个编译而另一个不编译,我建议你看看这个问题和答案。)

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

构造具有不同输出的c#代码,唯一的区别应该是Nullable<;int>;与内部

好吧,一个微不足道的例子是任何声明称为Nullable<T>的本地类型的东西;int将始终解析为global::System.Int32T?上的?后缀将始终解析成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){} }