Ken*_*ith 0 c# anonymous-types
我有这个方法:
private string serializeResult(string errorCode = null, string parameter1 = null, string parameter2 = null, string context = null)
{
return JsonConvert.SerializeObject(new
{
errorCode,
parameter1,
parameter2,
context
});
}
Run Code Online (Sandbox Code Playgroud)
现在,如果 context、errorCode、parameter1 或parameter2 为空,我不希望为匿名类型添加它们。
我怎样才能做到这一点而不测试所有类型的选项(我有更多的参数,这是一个较小的问题)?
不要搞乱匿名类,而是提供自定义 JSON 序列化设置:
return JsonConvert.SerializeObject(new
{
errorCode,
parameter1,
parameter2,
context
}, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Run Code Online (Sandbox Code Playgroud)
请注意,一般来说,有条件地从匿名类中删除值是没有意义的。假设您可以以某种方式做到这一点,如果您尝试访问会发生什么:
var anonClass = new
{
errorCode ?? removeIfNull, // fake syntax
parameter1,
parameter2,
context
};
anonClass.errorCode // will this access succeed? We don't know until runtime!
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1349 次 |
最近记录: |