Update:
§ 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.
This is none of these. The 4.0 compiler looks to be correct. Presumably it isn't happy because this in essence provides access to this
at a point when the type isn't initialized. Maybe ;-p
Note that I expect that it isn't really the this.someField
that causes this - more that the use of a field causes this
to be captured, meaning it wants to hoist the this
instance onto a compiler-generated class - as though you had written:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
The C# 3.0 compiler spots the above abuse of this
.
Reproduced. Investigating. It looks like an issue resolving the implicit this
in the constructor chaining.
The most likely workaround would be to use a virtual
method instead of a delegate, and simply override it in the derived class.
One workaround would be to pas the instance in as an argument, so the delegate becomes "obj => obj.whatever...", and use theDelegate(this);
.
Simpler repro:
public class MyBase {
public MyBase(Action a) { }
}
public class MySub : MyBase {
private string foo;
// with "this.", says invalid use of "this"
// without "this.", says instance required
public MySub() : base(delegate { this.foo = "abc"; }) { }
}
I would need to check the spec, but I'm not sure whether this
is valid in this context... so the 4.0 compiler could be correct.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…