Tep*_*epu 9 c# asp.net anonymous c#-4.0
我构建以下匿名对象:
var obj = new {
Country = countryVal,
City = cityVal,
Keyword = key,
Page = page
};
Run Code Online (Sandbox Code Playgroud)
我想只在其值存在时才在成员中包含成员.
例如,如果cityVal为null,我不想在对象初始化中添加City
var obj = new {
Country = countryVal,
City = cityVal, //ignore this if cityVal is null
Keyword = key,
Page = page
};
Run Code Online (Sandbox Code Playgroud)
这可能在C#中吗?
你不能那样做。
但您可以做的是提供这些属性的默认值(null?)。
var obj= new
{
Country= countryVal,
City = condition ? cityVal : null,
Keyword = condition ? key : null,
Page = condition ? page : null
};
Run Code Online (Sandbox Code Playgroud)
它甚至没有编码或反射的摆设,所以如果您确实需要这样做,那么您最终可以做if-else
if (string.IsNullOrEmpty(cityVal)) {
var obj = new {
Country = countryVal,
Keyword = key,
Page = page
};
// do something
return obj;
} else {
var obj = new {
Country = countryVal,
City = cityVal,
Keyword = key,
Page = page
};
//do something
return obj;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
好吧,你会有 if else 条件。但是,如果您使用 newtonsoft JSON 将其序列化为 JSON 对象,这可能会有所帮助:
var json = JsonConvert.SerializeObject(value, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3590 次 |
| 最近记录: |