为什么需要{}初始化一个Add方法? [英] Why is an Add method required for { } initialization?

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

问题描述

要使用这样的初始化语法:

To use initialization syntax like this:

var contacts = new ContactList
{
    { "Dan", "dan.tao@email.com" },
    { "Eric", "ceo@google.com" }
};



......我的理解是,我的 ContactList 需要定义需要两个字符串参数的添加方法:

...my understanding is that my ContactList type would need to define an Add method that takes two string parameters:

public void Add(string name, string email);



什么是有点混乱给我介绍这是在 {} 初始化语法似乎是最有用的只读或固定大小的集合。毕竟这是为了模仿初始化语法为的阵列的,对不对? (OK,所以数组不只读;但它们的固定大小。)自然它只能时集合的内容在编译时已知的(至少元件的数目),用于与

What's a bit confusing to me about this is that the { } initializer syntax seems most useful when creating read-only or fixed-size collections. After all it is meant to mimic the initialization syntax for an array, right? (OK, so arrays are not read-only; but they are fixed size.) And naturally it can only be used when the collection's contents are known (at least the number of elements) at compile-time.

所以,几乎看起来,使用这个集合初始化语法(有一个添加方法的主要要求,因此可变集合)是与在它是最有用的典型案例几率。

So it would almost seem that the main requirement for using this collection initializer syntax (having an Add method and therefore a mutable collection) is at odds with the typical case in which it would be most useful.

我敢肯定,我没有把尽可能多认为此事作为C#设计团队;它只是似乎有可能已为此语法将与它的典型应用场景网状更好的不同的规则。

I'm sure I haven't put as much thought into this matter as the C# design team; it just seems that there could have been different rules for this syntax that would have meshed better with its typical usage scenarios.

我是大错特错吗?是使用 {} 语法来初始化固定大小的集合,我觉得还不如普通的愿望?还有哪些其他因素可能影响对这个语法,我根本没有想到的要求制定?

Am I way off base here? Is the desire to use the { } syntax to initialize fixed-size collections not as common as I think? What other factors might have influenced the formulation of the requirements for this syntax that I'm simply not thinking of?

推荐答案

原因因为这是它被改装。我同意你的说法,使用一个构造函数取一个集合将使大大更有意义,但并不是所有的现有的集合类实现这个和变化应(1)与所有现有的收藏工作,(2)不改变任何现有的类方式。

The reason for this is that it was retrofitted. I agree with you that using a constructor taking a collection would make vastly more sense, but not all of the existing collection classes implemented this and the change should (1) work with all existing collections, (2) not change the existing classes in any way.

这是一种妥协。

这篇关于为什么需要{}初始化一个Add方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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