开发者

Object Initializer and Dynamically specifying properties

开发者 https://www.devze.com 2022-12-19 13:23 出处:网络
With an object initializer, is it possible to optionally include setting of property? For example: Request request = new Request

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
};


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
};   


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:

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

精彩评论

暂无评论...
验证码 换一张
取 消