这不是真正的问题,如果这是一个愚蠢的问题,我深表歉意,但这只是我很好奇的问题。假设我想在字符串不为 null 时将字符串参数解析为整数,否则将整数设置为 -1。有没有更好的方法来写这个语句:
int id = context.Request["Id"] == null ? -1 : int.Parse(context.Request["Id"]);
必须评估字符串以查看它是否为空,然后再次评估以解析它,这看起来很麻烦。现在我想到了,这已经提出了对象并访问对象属性(如果它不为空)。所以像这样:
int id = person == null ? -1 : person.id;
这是公认的做法吗?
最佳答案
对于您的第一个示例,您可以使用 null coalescing operator :
int id = int.Parse(context.Request["Id"] ?? "-1");
如果存在 null-safe dereferencing operator,则可以改进第二个示例但由于它在 C# 中不存在,所以您的方法很好:
int id = person == null ? -1 : person.Id;
关于C# 解析值如果不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11728498/