我有以下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
我做错了什么?
答案 0 :(得分:3)
信息非常清晰。没有任何成员在任何地方分配值。使用它们的属性是唯一的。
查看代码类型和推测用法,我建议使用参数化构造函数来设置这些字段的值。
答案 1 :(得分:1)
我认为您希望这些静态属性可以懒惰地初始化对象。你这样做的方式,他们从不设置私有字段,但继续创建新对象。所以你可能想这样做:
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;
}
}