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 = "" };
来源:https://stackoverflow.com/questions/2234091/object-initializer-and-dynamically-specifying-properties