【问题标题】:Trying to understand the inheritance chain试图理解继承链
【发布时间】:2017-07-20 11:40:58
【问题描述】:

下面是父子类。

public class ParentController : ApiController
{
   public ICustomer customer { get; set;}
   public ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //no issue here
    public string Get()
    {
       customer = util.GetCustomers();
     }

}

如果我将父类属性设置为受保护并尝试使用它们,我会得到Object NULL reference Exception

public class ParentController : ApiController
{
   protected ICustomer customer { get; set;}
   protected ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //Object Null reference exception at run time here
    public string Get(){
    customer = util.GetCustomers();}

}

我试图了解将public 更新为protected 访问说明符有何不同。

请注意:-

  • 我正在使用Castle Windsor DI 容器

请暂时忽略命名约定。

【问题讨论】:

  • @Kgn-web:不,该代码确实无法编译。你需要像public class ParentController : ApiController 这样的东西。然后你的 ChildController 代码也不会编译,因为你在类声明中直接有一个非声明。请提供minimal reproducible example。 (我还强烈建议您了解 .NET 命名约定。)
  • @JonSkeet,我的拼写错误。对此我深表歉意
  • 您的异常与编译器错误无关的原因可能是您从未在 ChildController-class 中实例化您的 utils-property。
  • @HimBromBeere,因为我提到我使用 DI Null 引用问题仅在将成员设为受保护时才会出现
  • @JonSkeet,我已经更正了我的帖子,您现在可以分享您的想法吗?谢谢

标签: c# inheritance asp.net-web-api dependency-injection access-specifier


【解决方案1】:

我猜您正在通过 AutoFac 之类的 IoC 容器实例化这些类的实例,并且您正在使用 setter 注入。否则我看不到第一个示例将如何工作,因为您从未初始化 util

当成员受到保护时,IoC 容器无法对其进行初始化。只有公共成员才能被类本身之外的代码访问。

【讨论】:

  • 是的。你猜对了。我正在使用 Castle Windsor DI 容器(仅供参考 - 我在帖子中提到过)
  • 真诚感谢您发布此信息。我不知道这一点。 :)
猜你喜欢
  • 1970-01-01
  • 2018-10-24
  • 2014-04-27
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多