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

标签 c# asp.net c#-4.0 anonymous

我构建了以下匿名对象:

var obj = new {
    Country = countryVal,
    City = cityVal,
    Keyword = key,
    Page = page
};

我只想在对象的值存在时将其包含在对象中。

例如如果cityVal为null,我不想在对象初始化时添加City

var obj = new {
    Country = countryVal,
    <del>City = cityVal, </del> //ignore this if cityVal is null 
    Keyword = key,
    Page = page
};

这在 C# 中可行吗?

最佳答案

它甚至不可能与 codedom 或反射一起使用,所以如果你真的需要这个,你最终可以做 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;
}

关于C# 对象初始化中的条件匿名对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985446/

相关文章:

c# - 递归 LINQ 查询函数中的嵌套索引

c# - 从字符串中删除重复值

c# - 字段和变量有什​​么区别?

asp.net - 如何查找哪个 Controller /操作发生错误?

asp.net - 选择文本作为所有文本列的数据类型是否有缺点?

c# - 如何在 C# 中向 Web 服务并行发出多个请求

c# - 为什么我们可以使用这样的任务?

c# - 如何在 Linux 上获取 CPU 温度

c# - 如何让泛型处理需要仔细转换的返回值?

c# - Asp.Net Boilerplate,如何获取当前登录用户?