对象初始化程序和动态指定属性
问题描述:
使用对象初始值设定项,是否可以选择包含属性设置?对象初始化程序和动态指定属性
例如:
Request request = new Request
{
Property1 = something1,
if(something)
Property2 = someting2,
Property3 = something3
};
答
不是我所知道的。很肯定你唯一的选择就是做这样的:
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
};
答
号对象initialisers被翻译成的一组语句哑序列。很明显,你可以通过黑客来实现类似的事情,比如将属性设置为默认值(例如new Request { Property2 = (something ? something2 : null) }
),但是设置者仍然会被调用 - 当然这会产生意想不到的后果如果Request的实施者决定更改属性的默认值。所以最好避免这种技巧,并通过以旧的对象初始化方式编写显式集合语句来执行任何条件初始化。
答
没有,因为这些是静态调用,它们不能根据某些条件在运行时删除或添加。
可以有条件地更改值,就像这样:
Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" };