0

以下是父級&子級。試圖瞭解繼承鏈

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();} 

} 

我想了解它是如何使差分更新publicprotected訪問符。

請注意: -

  • 我使用Castle Windsor DI容器

請忽略現在的命名約定。

+0

@ Kgn-web:不,該代碼真的不會編譯。你需要像'公共類ParentController:ApiController'。那麼你的'ChildController'代碼也不會編譯,因爲你在類聲明中直接聲明瞭一個非聲明。請提供[mcve]。 (我還強烈建議您瞭解.NET命名約定。) –

+0

@JonSkeet,我的排字錯誤。我真誠地爲此道歉 –

+0

您的異常的原因不在於您的編譯器錯誤,可能是因爲您從未在您的「ChildController」類中實例化您的「utils」屬性。 – HimBromBeere

回答

2

我猜你是通過像AutoFac這樣的IoC容器實例化這些類的實例,並且你正在使用setter注入。否則,我看不到第一個例子會如何工作,因爲您從不初始化util

當成員受保護時,IoC容器無法初始化它。只有公共成員可以通過課堂外的代碼進行訪問。

+0

是的。你猜對了。我正在使用Castle Windsor DI容器(僅供參考 - 我在文章中提到過) –

+0

真誠感謝您發佈此信息。我不知道這一點。 :) –