C#-为什么无法在字段初始化程序中访问“ this”? [英] C# - why is it not possible to access 'this' in a field initializer?

查看:62
本文介绍了C#-为什么无法在字段初始化程序中访问“ this”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会产生编译器错误:

Why does this produce a compiler error:

class Foo
{
    public Bar Baz = new Bar(this);
}

但这不是:

class Foo
{
    public Bar Baz;

    public Foo()
    {
        this.Baz = new Bar(this);
    }
}

概念上两者是相等的,不是吗? / p>

Conceptually the two are equivalent, are they not?

推荐答案

不,它们并不完全相同...变量初始值设定项在任何基类之前执行构造函数运行。构造函数的主体在运行基类构造函数之后执行。 (这与Java不同,在Java中变量初始化程序在基类构造函数之后但在构造函数主体之前执行。)

No, they're not quite equivalent... the variable initializer executes before any base class constructors are run. The body of the constructor executes after base class constructors are run. (This is different from Java, where variable initializers execute after base class constructors but before the constructor body.)

因此,访问 this 在构造函数主体中:您可以确定至少已针对对象的基类(向上)初始化了该对象。

Therefore it's safer to access this within the constructor body: you can be sure that the object is initialized at least in respect to its base class (and upwards).

I 相信这就是原因,

这篇关于C#-为什么无法在字段初始化程序中访问“ this”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆