[英]Object Initializer and Dynamically specifying properties
使用對象初始化程序,是否可以選擇包含屬性設置?
例如:
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;
或者你可以像這樣做,如果有一個默認值/ null值你可以設置為:
Request request = new Request
{
Property1 = something1,
Property2 = something ? someting2 : null,
Property3 = something3
};
否。對象初始化器被轉換為一組啞語句集。
顯然,你可以做hacks來實現類似的東西,比如將屬性設置為你知道的默認值(例如new Request { Property2 = (something ? something2 : null) }
),但是setter仍然會被調用 -當然,如果Request的實施者決定更改屬性的默認值,這將產生意想不到的后果。 所以最好避免這種技巧,並通過以舊的pre-object-initialiser方式編寫顯式set語句來進行任何條件初始化。
不,因為這些是靜態調用,所以無法在運行時根據某些條件刪除或添加它們。
您可以有條件地更改值,如下所示:
Foo foo = new Foo { One = "", Two = (true ? "" : "bar"), Three = "" };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.