为什么派生类的字段初始值设定项在基类的初始值设定项之前执行 [英] Why are field initializers of a derived class are executed before base classes's initializers

查看:142
本文介绍了为什么派生类的字段初始值设定项在基类的初始值设定项之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数按从上到下的顺序执行。 base首先跟随派生的。这个安排是基于一个重要的OOP保证,一个对象(这里的基础)必须始终在它被使用之前被初始化(这里是派生类的构造函数)。

constructors are executed in the order from top to bottom I.E. base's first followed by derived one. This arangement is based on an important OOP assurance that an object (base here) must always be initialized before it can be used (here in derived class's constructor).

我'我想知道为什么现场初始化器在C#中不遵循这个原则?我在这里遗漏了什么吗?

I'm wondering why field-initializers do not follow this principle in C#? Am I missing something here?

我也发现了这个原理在字段初始化器中的用处。我有一个基类,其属性返回Identity对象。每个派生类都有自己的存储库字段,我一直使用field-initializer初始化(使用默认构造函数)。最近我决定还必须为存储库类提供Identity对象,因此我在存储库构造函数中引入了一个额外的参数。但我很难找到:

I've come across a usefulness of this principle with field-initializers as well. I have a base class with a property returning Identity object. Every derived class has its own repository field which I have been initializing using field-initializer (using default constructor). Recently I've decided that the repository class must also be provided with Identity object so I introduced an extra argument in the repository constructor. But I'm stuck to find out:

public class ForumController : AppControllerBase
{
        ForumRepository repository = new ForumRepository(Identity);
    // Above won't compile since Identity is in the base class.

   // ... Action methods.
}

现在我只剩下一个选项来丰满我的每个控制器使用默认构造函数,仅用于使用Identity初始化存储库对象。

Now I'm left with only one option that is to plump my every controller with a default constructor for only to do the job of initializing of repository object with Identity.

推荐答案


为什么派生类的字段初始值设定项在基类字段初始值设定项之前执行?

Why are field initializers of a derived class executed before the base class field initializers?

好问题。我在2008年的这些博文中回答了你的问题:

Good question. I answered your question in these blog posts from 2008:

http://blogs.msdn.com/b/ericlippert/archive /2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as- constructors-part-two.aspx

这篇关于为什么派生类的字段初始值设定项在基类的初始值设定项之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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