对象初始化中的C#条件匿名对象成员

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#中吗?

Ser*_*rge 5

你不能那样做。

但您可以做的是提供这些属性的默认值(null?)。

var obj=  new
            {
                Country= countryVal,
                City = condition ? cityVal : null,
                Keyword = condition ? key : null,
                Page = condition ? page : null
            };
Run Code Online (Sandbox Code Playgroud)

  • 是的,您可以使用三元运算符:| (2认同)
  • 您可以使用三元运算符,但它仍然会将字段添加到对象中。但它会有一个空值。我认为这是正确的方法,应该调整代码以处理或忽略空值。 (2认同)

Tep*_*epu 5

它甚至没有编码或反射的摆设,所以如果您确实需要这样做,那么您最终可以做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)

  • 实际上,这非常有用。它解决了我的问题 (2认同)