为什么不能使用c#对象初始化器语法调用方法? [英] Why can't you call methods with c# object initializer syntax?

查看:61
本文介绍了为什么不能使用c#对象初始化器语法调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能使用c#对象初始值设定项语法调用方法?

Why can't you call methods with c# object initializer syntax?

在我看来,属性设置器的调用顺序与它们在语法中设置的顺序相同,那么为什么也不允许调用方法呢?如果有充分的理由,我会想念它.

It seems to me that the property setters are called in the order that they are set in the syntax, so why not allow calls to methods as well? If there is a good reason, I'm missing it.

我意识到方法和属性之间的语义差异以及技术上的相似性.这个问题的目的是出于良好的技术原因,探究它们不包含该功能.

I realize the semantic differences between methods and properties and the technical similarities. The purpose of this question is to probe for a good technical reason that they did not include the feature.

这个.__curious_geek,我听到您在说什么,但是我确定他们没有包含某些功能,因为从技术上讲这是不可行的.

this. __curious_geek, I hear what you are saying, but I'm sure there are some features they haven't included because it wasn't technically feasable.

仅此而已.响亮而清晰地听到了压倒性的令人不快的声音.Stackoverflow不再是问答站点".而是捍卫您的问题站点".

That's all I'm after. The overwhelming unwelcoming tone is heard loud and clear. Stackoverflow is no longer a "Question and Answer site" but instead a "Defend your question site".

样品用量:

var mySuperLongVariableNameThatIDontWantToTypeOverAndOverAgainAndIsntThatTheWholePointAnyway  = new Thingy
    {
        Name = "Marty McFly",
        AddChildren("Biff","Big Bird","Alf"),
        // 1000 other properties and method calls.....
    }

推荐答案

答案就在名字中–对象 initializer 语法是一种语法糖,可以直观地对对象的初始状态进行分组.方法会更改对象状态,因此一旦更改,它就不再是初始状态.

The answer is in the name -- object initializer syntax is syntactic sugar to visually group the object's initial state. Methods change the object state, so once it's changed, it's no longer the initial state.

例如:假设您买车.这是一辆搭载55,000英里的红色小轿车.然后,您决定驱动它.最终达到55,500英里.它已从其初始状态更改:

For example: say you buy a car. It is a red coupe with 55,000 miles on it. Then, you decide to drive it. It ends up with 55,500 miles on it. It has changed from its initial state:

var c = new Car() {Color = "Red",
                   Style = Styles.Coupe,
                   Mileage = 55000};
// c.Mileage is 55,000
c.Drive();
// c.Mileage is 55,500

在这个有些人为的示例中,该方法具有副作用,因此将对象从其最初的55,000mi状态更改为55,500mi状态.这与购买拥有55,500英里行驶距离的汽车不同.

In this somewhat contrived example, the method has a side effect and thus changes the object from its initial 55,000mi state to a 55,500mi state. This is not the same thing as buying a car with 55,500 miles on it.

这篇关于为什么不能使用c#对象初始化器语法调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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