我应该使用对象初始化程序还是构造函数? [英] Should I use an object initializer or a constructor?

查看:80
本文介绍了我应该使用对象初始化程序还是构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解了对象初始化器,并且想知道何时使用它们的最佳实践是什么.

I have just learned about object initializers and was wondering what the best practices for when to use them are.

这是我对它们的了解: http://msdn. microsoft.com/en-us/library/vstudio/bb384062.aspx 很明显,它们对于创建匿名类型是必需的,但是我想知道在所有其他情况下是否应该尝试将它们比普通构造函数更喜欢.

This is what I read about them: http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx It makes it clear that they are necessary for creating anonymous types but I would like to know if I should try to prefer them to normal constructors in all the other cases.

推荐答案

我目前在使用它们时遇到以下问题:

I currently see the following problems with using them:

  1. 分配的属性必须是可更改的.好像 不可取,因为如果将数据传递给构造函数,我可以 如果提供的数据是,请在此处进行检查并使对象创建失败 不足或错误.如果可以使用属性I分配数据 突然不得不弄清楚我对象的状态是什么,是否 一切都已正确创建,或者我可能处于其他状态 内.
  2. 分配的属性必须是公共的.这意味着必须公开访问原本可能是私有的内容,然后再使用接口或类似的方式对其进行限制.
  1. The properties that are assigned have to be changeable. This seems undesirable because if the data is passed to a constructor I can check it there and make object creation fail if the data provided is insufficient or wrong. If data can be assigned with a property I suddenly have to figure out what the state of my object is, whether everything is properly created yet or which other state I might be in.
  2. The properties that are assigned have to be public. This means that access to things that might otherwise be private will have to be exposed and then later restricted by using an interface or something like that.

所以我的工作原理是:不要使用对象初始化程序来鼓励愚蠢的事情.

So my working theory is: Don't use object initializers they encourage stupid things.

这篇关于我应该使用对象初始化程序还是构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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