Object Initializer and Dynamically specifying properties

瘦欲@ 提交于 2019-12-01 02:54:09

问题


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

回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2234091/object-initializer-and-dynamically-specifying-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!