我在这里讨论与C#中实例方法/属性的作用域的差异.这是代码:
public class Base { public EventHandler Click {get;set;} public Base(EventHandler clickHandler) { this.Click = clickHandler; } } public class Derived: Base { public Derived(): base((sender,e) => Execute()) { } private void Execute() { } }
代码在MonoDevelop 3.0上编译得很好,但在VS2010中给出了一个错误:
非静态字段,方法或属性“Base.Execute”需要对象引用
基本上,它归结为这样一个事实:当从派生类的构造函数调用基类的构造函数时,MS的C#编译器不允许访问派生类的方法/属性等.如何?
解决方法@H_403_10@
VS编译器遵循规范.不确定在Mono实现中允许它的原因是什么.
C# Specification,第10.11.1节构造函数初始值设定项:
An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer,as is it a compile-time error for an argument expression to reference any instance member through a simple-name.
C# Specification,第10.11.1节构造函数初始值设定项:
An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer,as is it a compile-time error for an argument expression to reference any instance member through a simple-name.