【问题标题】:AppSettings value is returning null in ternary operatorAppSettings 值在三元运算符中返回 null
【发布时间】:2014-02-26 09:05:25
【问题描述】:

我一直在将一些字符串值移动到我的 Web 配置中,但是,当用作三元运算符中的条件时,一个值返回 null。

网页配置:

<add key="Main.Root" value="www.blah.com" />

AppSettings.cs:

public struct SiteRoots
{
   public static readonly string Test = ConfigurationManager.AppSettings["Main.Root"];
}

代码:

 ViewBag.Profile = HttpContext.IsDebuggingEnabled || HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live;

如果我在页面上的其他任何地方使用“AppSettings.SiteRoots.Test”,它会返回正确的值,它似乎只在用作三元运算符内的条件时返回 null。

【问题讨论】:

  • 如果您认为三元运算符是问题所在,那么只需将其转换为 if-else 语句,看看它是否会消失。

标签: c#


【解决方案1】:

ternary 表达式括在括号中,同时确保AppSettings.GTMKeys.TestAppSettings.GTMKeys.Liveboolean 赋予它可以与|| 一起使用。

ViewBag.Profile = HttpContext.IsDebuggingEnabled || (HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live);

您的表达式中可能不需要 HttpContext.IsDebuggingEnabled

ViewBag.Profile = HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live;

【讨论】:

  • 他的本意不是ViewBag.Profile = (...) ? Test : Live吗?
猜你喜欢
  • 1970-01-01
  • 2014-09-24
  • 2016-03-09
  • 1970-01-01
  • 2020-02-09
  • 2020-08-02
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
相关资源
最近更新 更多