协变的对象初始化? [英] covariant object initializers?

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

问题描述

有人说我有一个属性,它是一本字典℃的类,字符串,布尔和使用对象初始化我可以用这个语法(我认为看起来pretty的清洁)GT ;,:

say that I have an class that has a property that is a dictionary<string,bool>, using a object initializer I can use this syntax (which I think looks pretty clean):

new MyClass()
{
  Table = { {"test",true},{"test",false} }
}

不过,初始化之外,我不能做到这一点:

however, outside of the initializer I can't do this:

this.Table = { {"test",true},{"test",false} };

为什么初始化一个特例?我大胆猜测,它是与LINQ要求,协方差或诸如此类的东西,但感觉有点不协调不能够使用那种初始的无处不在......

Why are initializers a special case? I'd hazard a guess that it has something to do with LINQ requirements, covariance or whatnot but it feels a little incongruent not being able to use that kind of initializer everywhere...

推荐答案

现在的问题是有点混乱,因为这个问题已经无关,与LINQ,无关的通用方差,并设有一个集合初始化,以及一个对象初始化。真正的问题是,据我可以告诉为什么是不合法的使用集合初始化的对象创建EX pression外?

The question is somewhat confusing, as the question has nothing to do with LINQ, nothing to do with generic variance, and features a collection initializer, as well as an object initializer. The real question is, as far as I can tell "why is it not legal to use a collection initializer outside of an object creation expression?"

这里的相关的设计原理是,在一般情况下,我们希望该创建和初始化的对象为具有新字在其中某处作为信号给读者,有一个对象创建这里发生的操作。 (是的,有一些例外情况在C#这条规则。作为一个练习的读者,看看你是否可以命名它们。)

The relevant design principle here is that in general, we want operations that create and initialize objects to have the word "new" in them somewhere as a signal to the reader that there is an object creation happening here. (Yes, there are a few exceptions to this rule in C#. As an exercise to the reader, see if you can name them all.)

做事情的方式使得它更难推理的code。快速,这是什么呢?

Doing things your way makes it harder to reason about the code. Quick, what does this do?

d = new List<int>() { 10, 20, 30 };
d = { 40, 50, 60 };

请问第二行的追加的40,50,60现有的名单?抑或是一个新的取代旧的名单?有没有新在那里,所以没有读者有一个期望,一个新的对象被创建?

Does the second line append 40, 50, 60 to the existing list? Or does it replace the old list with a new one? There's no "new" in there, so does the reader have an expectation that a new object has been created?

当你说

q = new Whatever() { MyList = { 40, 50, 60 } };

这不创建一个新的列表;追加40,50,60,以由构造分配现有列表。你提出的语法,因此不明确和混乱,以一个新的列表是否创建与否。

that doesn't create a new list; it appends 40, 50, 60 to an existing list allocated by the constructor. Your proposed syntax is therefore ambiguous and confusing as to whether a new list is created or not.

建议的特点是既混乱和不必要的,所以它不可能很快实现的任何时间。

The proposed feature is both confusing and unnecessary, so it's unlikely to be implemented any time soon.

这篇关于协变的对象初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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