仅当属性不为空时才将属性添加到匿名类型 C#

Add Properties to anonymous type only if they are not null C#

我有这个方法:

private string serializeResult(string errorCode = null, string parameter1 = null, string parameter2 = null, string context = null)
{
    return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    });
}

现在如果context、errorCode、parameter1 或parameter2 为null,我不想为匿名类型添加它们。

如何在不测试所有选项的情况下做到这一点(我有更多的参数,这是一个较小的问题)?

与其搞乱匿名 class,不如提供自定义 JSON 序列化设置:

return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    }, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

请注意,一般情况下,有条件地从匿名 class 中删除值是没有意义的。假设你能以某种方式做到这一点,如果你试图访问会发生什么:

var anonClass = new
    {
        errorCode ?? removeIfNull, // fake syntax
        parameter1,
        parameter2,
        context 
    };
anonClass.errorCode // will this access succeed? We don't know until runtime!

您可以忽略来自序列化程序的 null 值,如下所示。另请参考How to ignore a property in class if null, using json.net

return JsonConvert.SerializeObject(new
{
    errorCode,
    parameter1,
    parameter2,
    context 
}, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});