【问题标题】:Field ... is never assigned to, and will always have its default value null字段 ... 永远不会分配给,并且始终具有其默认值 null
【发布时间】:2014-03-09 14:22:08
【问题描述】:

我有以下HandleErrorModule 类:

public sealed class HandleErrorModule : IHttpModule {
    private static ILogger _logger;
    private static CustomErrorsSection _section;
    private static Dictionary<HttpStatusCode, String> _views;

    private static CustomErrorsSection CustomErrorsSection { 
      get { 
        if (_section != null) 
          return _section;
        else 
          return WebConfigurationManager.GetWebApplicationSection("system.web/customErrors") as CustomErrorsSection; 
      } 
    }

    private static ILogger Logger { 
      get { return (_logger != null) ? _logger : ObjectFactory.GetInstance<ILogger>(); }
    }

    private static Dictionary<HttpStatusCode, String> Views { 
      get { 
        if (_views != null) 
          return _views;
        else
          return new Dictionary<HttpStatusCode, String> { { HttpStatusCode.NotFound, "NotFound_" }, { HttpStatusCode.InternalServerError, "Internal_" } }; 
       } 
    }

    public void Init(HttpApplication application) {

       // Handle error code.
       // Here I access CustomErrorsSection, Logger and Views properties

    }

在收到警告:

字段 'HandleErrorModule._views' 从未分配给,并且始终具有其默认值 null 字段“HandleErrorModule._section”从未分配给,并且始终具有其默认值 null 字段 'HandleErrorModule._logger' 从未分配给,并且始终具有其默认值 null

我做错了什么?

【问题讨论】:

  • 警告非常清楚。您永远不会为这些变量分配任何值,因此它们将始终为空。您可以通过为变量赋值或完全删除它们来“解决这个问题”,因为它们从未被使用过。
  • 例如,_viewsprivate,而您的任何 private 方法或属性都不会为其赋值。因为它是private,所以编译器知道没有其他代码也有机会设置它的值。因此警告。

标签: c#


【解决方案1】:

信息非常清晰。任何成员都没有在任何地方分配值。使用它们的属性是 get only。

查看代码类型和假定用法,我建议使用可以为这些字段设置值的参数化构造函数。

【讨论】:

    【解决方案2】:

    我认为您希望这些静态属性延迟初始化对象。但是,按照您的方式,他们从不设置私有字段,而是继续创建新对象。所以你可能想这样做:

    private static Dictionary<HttpStatusCode, String> Views
    {
        get
        {
            // when the private field is null, initialize the value
            if (_views == null)
            {
                _views = new Dictionary<HttpStatusCode, String> {
                        { HttpStatusCode.NotFound, "NotFound_" },
                        { HttpStatusCode.InternalServerError, "Internal_" } };
            }
    
            // and always return the private field
            return _views;
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多