对象初始值设定项和动态指定属性
使用对象初始值设定项,是否可以选择包含属性设置?
例如:
Request request = new Request
{
Property1 = something1,
if(something)
Property2 = someting2,
Property3 = something3
};
With an object initializer, is it possible to optionally include setting of property?
For example:
Request request = new Request
{
Property1 = something1,
if(something)
Property2 = someting2,
Property3 = something3
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知。很确定你唯一的选择是这样做:
或者如果有默认/空值,你可以将其设置为:
Not that I'm aware of. Pretty sure your only option is to do it like this:
Or you could do it like this if there's a default/null value you can set it to:
不。对象初始值设定项被转换为一组愚蠢的 set 语句序列。
显然,您可以通过一些技巧来实现类似的目标,例如将属性设置为您知道的默认值(例如
new Request { Property2 = (something ? Something2 : null) }
),但是setter 仍然会被调用——当然,如果 Request 的实现者决定更改属性的默认值,这会产生意想不到的后果。因此,最好避免这种技巧,并通过以旧的预对象初始化方式编写显式设置语句来执行任何条件初始化。No. Object initialisers are translated into a dumb sequence of set statements.
Obviously, you can do hacks to achieve something similar, like setting the property to what you know the default value to be (e.g.
new Request { Property2 = (something ? something2 : null) }
), but the setter's still gonna get called -- and of course this will have unintended consequences if the implementer of Request decides to change the default value of the property. So best to avoid this kind of trick and do any conditional initialisation by writing explicit set statements in the old pre-object-initialiser way.不,由于这些是静态调用,因此无法根据某些条件在运行时删除或添加它们。
您可以有条件地更改该值,如下所示:
No, since those are static calls they can't be removed or added at runtime based on some condition.
You can change the value conditionally, like so: