对象初始值设定项和动态指定属性

发布于 2024-08-21 01:21:11 字数 246 浏览 6 评论 0原文

使用对象初始值设定项,是否可以选择包含属性设置?

例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

油饼 2024-08-28 01:21:11

据我所知。很确定你唯一的选择是这样做:

Request request = new Request
{
    Property1 = something1,
    Property3 = something3
};
if(something)
    request.Property2 = someting2;

或者如果有默认/空值,你可以将其设置为:

Request request = new Request
{
    Property1 = something1,
    Property2 = something ? someting2 : null,
    Property3 = something3
};   

Not that I'm aware of. Pretty sure your only option is to do it like this:

Request request = new Request
{
    Property1 = something1,
    Property3 = something3
};
if(something)
    request.Property2 = someting2;

Or you could do it like this if there's a default/null value you can set it to:

Request request = new Request
{
    Property1 = something1,
    Property2 = something ? someting2 : null,
    Property3 = something3
};   
吹泡泡o 2024-08-28 01:21:11

不。对象初始值设定项被转换为一组愚蠢的 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.

有木有妳兜一样 2024-08-28 01:21:11

不,由于这些是静态调用,因此无法根据某些条件在运行时删除或添加它们。

您可以有条件地更改该值,如下所示:

Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" };

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:

Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文