gpt4 book ai didi

c# - 为什么三元运算符不是这样工作的?

转载 作者:行者123 更新时间:2023-11-30 19:10:43 27 4
gpt4 key购买 nike

为什么不编译?以下代码有什么问题?

(_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext;

如果我根据是否编译来重申它:

 if (_DbContext == null)
return _DbContext = new ProductAndCategoryEntities();
else return _DbContext;

最佳答案

条件表达式中 : 两边的内容是表达式,而不是语句。他们必须评估一些值(value)。 return (anything) 是一个语句而不是表达式(例如,你不能说 x = return _DbContext;),所以它在那里不起作用。

不过,

new ProductAndCategoryEntities()_DbContext 似乎都是表达式。因此,您可以将 return 移到条件表达式的外部。

return (_DbContext == null) ? (_DbContext = new ProductAndCategoryEntities()) : _DbContext;

不过,在这种情况下,最好不要使用 ?: 并直接使用 if

if (_DbContext == null) _DbContext = new ProductAndCategoryEntities();
return _DbContext;

这更直接一点。返回赋值的值通常看起来有点粗略。

关于c# - 为什么三元运算符不是这样工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074994/

27 4 0
文章推荐: javascript - 对象有时无法在 IE 8 中访问
文章推荐: c# - List 到 List C#