【发布时间】: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