为什么你不能用'这个'的成员初始化? [英] Why can't you use 'this' in member initializers?

查看:89
本文介绍了为什么你不能用'这个'的成员初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
无法这个的成员初始使用?

任何想法,为什么,如果我尝试做这样的事情,我得到一个错误:

Any ideas why I get an error if I try to do something like this:

public class Bar
{
    public Bar(Foo foo)
    {
    }
}

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



我得到一个错误说:

I get an error saying:

不能使用这个的成员初始

"Cannot use 'this' in member initializer"

但以下工作:

public class Foo
{
    private Bar _bar;

    public Foo()
    {
        _bar = new Bar(this);
    }
}



任何人都知道这背后的原因是什么?我的理解是,这些国家将编译到相同的IL,所以很好奇,为什么一个是允许的,另一种是不。

Anyone know the reason behind this? My understanding was that these would compile to the same IL, so am curious as to why one is allowed and the other isn't.

谢谢,
亚历克斯

Thanks, Alex

推荐答案

我的犯罪嫌疑人的是要阻止你使用对象之前的至少的基类构造函数运行,确保所有的基类成员进行适当初始化。 (变量初始化被执行的的基类构造函数,而执行构造函数体的之后的这一点。)

I suspect it's to prevent you from using the object before at least the base class constructor has run, ensuring that all the base class members are appropriately initialized. (Variable initializers are executed before the base class constructor, whereas the constructor body is executed after that.)

将检查注明规格是否有什么说这个的时候,我下个吧...

Will check whether the annotated spec has anything to say about this when I'm next near it...

编辑:C#4注释规范没有任何解释。只是(在10.5.5.2):

The C# 4 annotated spec doesn't have any explanation. Just (in 10.5.5.2):

一个变量初始化了一个实例字段不能引用正在创建的实例

A variable initializer for an instance field cannot reference the instance being created.

这篇关于为什么你不能用'这个'的成员初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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