(此== NULL)在C#! [英] (this == null) in C#!
问题描述
由于被固定在C#4中的错误,下面的程序打印真正
。 (试着在LINQPad)
无效的主要(){新的派生(); }
类基地{
公共库(Func键<串GT; valueMaker){Console.WriteLine(valueMaker()); }
}
类派生:基{
串CheckNull(){回报?我是NULL+(这== NULL); }
公共派生():基座(()=> CheckNull()){}
}
在VS2008在Release模式,它抛出一个InvalidProgramException。 (在调试模式下,它工作正常)
在VS2010 Beta 2中,它不编译(我没有尝试测试版1);我了解到,艰难地
有没有其他办法让此== NULL
纯C#<? / p>
此观察已经张贴在计算器中的另一个问题更早。
马克的的大问题的答案表示根据规范(第7.5.7),你不应该能够访问这个
在这种情况下,并在C#3.0编译器有能力这样做是一个错误。 C#4.0编译器根据该规范行为正确(即使在Beta 1中,这是一个编译时错误):
§ 7.5.7这种访问
A 此访问的由保留字的
这个$ 。C $ C>
的此访问:的
这
A 此访问的只允许在在块的实例构造函数,实例方法或实例访问。
块引用>Due to a bug that was fixed in C# 4, the following program prints
true
. (Try it in LINQPad)void Main() { new Derived(); } class Base { public Base(Func<string> valueMaker) { Console.WriteLine(valueMaker()); } } class Derived : Base { string CheckNull() { return "Am I null? " + (this == null); } public Derived() : base(() => CheckNull()) { } }
In VS2008 in Release mode, it throws an InvalidProgramException. (In Debug mode, it works fine)
In VS2010 Beta 2, it doesn't compile (I didn't try Beta 1); I learned that the hard way
Is there any other way to make
this == null
in pure C#?解决方案This observation has been posted on StackOverflow in another question earlier today.
Marc's great answer to that question indicates that according to the spec (section 7.5.7), you shouldn't be able to access
this
in that context and the ability to do so in C# 3.0 compiler is a bug. C# 4.0 compiler is behaving correctly according to the spec (even in Beta 1, this is a compile time error):§ 7.5.7 This access
A this-access consists of the reserved word
this
.this-access:
this
A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.
这篇关于(此== NULL)在C#!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!