为什么委托中"this"指针为空?

Dav*_*ave 7 .net c#

我有以下代码(为清楚起见,删除了详细信息):

    private abstract class Base<TResult> {
        private readonly System.Func<TResult> func = null;

        protected Base(System.Func<TResult> func) {
            this.func = func;
        }

        public TResult Execute() {
            return this.func();
        }
    }

    private class Derived : Base<bool> {
        public Derived(bool myValue) : base(delegate() { return this.MyValue(); }) {
            this.myValue = myValue;
        }

        private bool myValue = false;
        private bool MyValue() {
            return this.myValue; // The "this" pointer is null here...
        }
    }

    Derived d = new Derived(true);
    bool result = d.Execute(); // This results in a null reference pointer (commented above)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

谢谢,戴夫

Mar*_*ell 6

这甚至合法吗?this在那时没有定义.IIRC,这是一个编译器错误 - 已在4.0中修复.

这是在4.0编译器中:

错误1关键字'this'在当前上下文中不可用C:\ Users\Marc\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 22 40 ConsoleApplication1

引用7.5.7:

在实例构造函数,实例方法或实例访问器的块中允许此访问.它具有以下含义之一:

(我的)

...

在上面列出的上下文中的primary-expression中使用this是编译时错误.特别是,无法在静态方法,静态属性访问器或字段声明的变量初始化程序中引用它.

在给出的示例中,它只是无效.


Cra*_*ntz 5

使用this在构造函数中总是危险的(除非你在哪里调用兄弟构造的特殊情况).您的Derived构造函数this在其调用时捕获,因为尚未构造实例,所以它为null.