2014-10-31 38 views
0

我從this article複製了此代碼,我不明白爲什麼將類內部的類定義爲屬性。另外,當類PersonalLoan被實例化時會發生什麼?將類聲明爲另一個類中的屬性

public class PersonalLoan 
{ 
    public string AccountNumber { get; set; } 
    public string AccounHolderName { get; set; } 
    public Loan LoanDetail { get; set; } 
    public PersonalLoan(string accountNumber) 
    { 
     this.AccountNumber = accountNumber; 
     this.AccounHolderName = "Sourav"; 
     this.LoanDetail = new Loan(this.AccountNumber); 
    } 
} 
public class Loan 
{ 
    public string AccountNumber { get; set; } 
    public float LoanAmount { get; set; } 
    public bool IsLoanApproved { get; set; } 
    public Loan(string accountNumber) 
    { 
     Console.WriteLine("Loan loading started"); 
     this.AccountNumber = accountNumber; 
     this.LoanAmount = 1000; 
     this.IsLoanApproved = true; 
     Console.WriteLine("Loan loading started"); 
    } 
} 
+3

你在哪裏看到一個類作爲屬性? – 2014-10-31 15:10:29

+6

如果你問這個'公共貸款LoanDetail {get;組; }',那麼它是[Composition](http://en.wikipedia.org/wiki/Object_composition)。您可能還會看到:[構圖與聚合之間的區別](http://www.c-sharpcorner.com/UploadFile/pcurnow/compagg07272007062838AM/compagg.aspx) – Habib 2014-10-31 15:10:38

+0

@Habib謝謝,請您告訴我, PersonalLoan'被實例化? – Constantine 2014-10-31 15:15:20

回答

3

我懷疑此代碼段是你應該避免的例子:一類PersonalLoanLoan類型的LoanDetail財產表明一個有-A類之間的關係。換句話說,這個代碼片斷的作者正試圖說

個人貸款具有貸款

然而,這是不太可能的關係,他們正試圖模型:在現實中,

個人貸款是一種貸款

的關係是,一個使用繼承進行建模,而不是組成。換句話說,他們應該這樣寫:

public class PersonalLoan : Loan { 
    public PersonalLoan(string accountNumber) : base(accountNumber) { 
     ... 
    } 
    ... 
} 

指向模型是不正確的另一個問題是,無論PersonalLoanLoan裏面有相同的accountNumber,存儲在兩個地方同一個對象中。當你看到這件事時,你知道有什麼不對。你得到兩個帳號的原因是當PersonalLoan得到實例化時,它的構造函數也實例化了Loan,並傳遞給它相同的accountNumber

這並不是說在別的對象內嵌入對象是錯誤的。例如,如果你是一個借款人地址作爲類模型,你最終會得到這樣的:

class Address { 
    public string Country {get;set;} 
    public string City {get;set;} 
    ... // And so on 
} 
class Borrower { 
    public Address MailingAddress {get;set;} 
    ... // 
} 

這種模式是非常有效的,因爲借款人有一個地址

+0

它是關於懶惰 http://www.c-sharpcorner.com/UploadFile/dacca2/implement-lazy-loading-in-C-Sharp-using-lazyt-class/ – Constantine 2014-10-31 15:25:24

+0

@Constantine模型文章在鏈接禮物並不理想,因爲它不符合實際,足以讓讀者直觀。 – dasblinkenlight 2014-10-31 15:30:50

+0

@dasblinkenlight我認爲這個名字是錯的。它應該是「LoanDetail」來匹配現實世界,因爲我已經看到了與現實世界中相同的結構。帶有'LoanDetails'子元素的'MyLoanTypeObject'。 – TyCobb 2014-10-31 15:33:55

相關問題