2013-10-09 2 views
2

간단한 질문처럼 보일지 모르지만, 어떤 이유로 나는 여러 오브젝트가있는 오브젝트를 가지고 있다는 개념에 두뇌를 부여하는 데 문제가 있습니다. 예를 들어 헤더와 바닥 글이 여러 개있는 객체가 있다고 가정 해 보겠습니다.오브젝트 내에서 오브젝트 클래스 생성하기

보고서처럼 헤더의 이름과 주소도 같습니다. 꼬리말에는 구입 한 품목의 합계가 있습니다. 그 사이에 부품 번호, 설명 및 가격이있는 품목이 있습니다.

머리글, 바닥 글 및 광고 항목 개체의 배열을 가진 개체를 모두 가질 수 있습니다. 모두 자체 속성이 있습니다. 예를 들어 보고서를 사용하고 있는데, 이는 내 질문에 대해 자세히 설명 할 수있는 유일한 개념이기 때문입니다.

누군가이 유형의 개체를 만드는 방법에 대한 링크를 보내거나 설명 할 수 있습니까?

VS 2010 및 VB.net을 사용하고 있으며 C#에서 VB로 변환 할 수 있습니다.

Report Object 
     Header Object 
     Property Name 
     Property Date 
     End 
     LineItem() Array Object 
     Property Part Number 
     Property Part Description 
     Property Number of Items 
     Property Per Item Price 
     Property Total price 
     End 
     Footer Object 
     Property Total Items count 
     Property Total Price 
     End 
    End 
+1

그것보다 구체적인합니다. 이것은 실제로보고 (시퀀스 중요)에 관한 것입니까, 아니면 더 일반적으로 클래스 디자인입니까? –

+2

답변을 얻은 것 같습니다. 'LineItems' 콜렉션을 나타내는 속성과 속성을 가진 헤더 객체. 이것은 매우 합리적으로 들립니다. – Khan

+0

클래스 기반 속성 솔루션 (아래 참조)은 콘텐츠 만 저장할 수 있습니다. 모든 레이아웃 지식 (예 : 머리글이 맨 위에 표시됨)은 다른 방식으로 저장해야합니다. –

답변

4

제프, C#에서와 가장 기본적인에서 :

public class Report 
{ 
    // typical simple property in report 
    public string ReportUid { get; set; } 
    // object properties 
    public Header Header { get; set; } 
    public Body Body { get; set; } 
    public Footer Footer { get; set; } 

    public Report() 
    { 
     Header = new Header(); 
     Body = new Body(); 
     Footer = new Footer(); 
    } 

    internal void CalculateFooterTotals() 
    { 
     // summerize the lineitems values in the footer 
     Footer.TotalItems = Body.LineItems 
      .Sum(x => x.Quantity); 
     Footer.TotalPrice = Body.LineItems 
      .Sum(x => x.Total); 
    } 
} 

public class Header 
{ 
    public string Name { get; set; } 
    public DateTime Date { get; set; } 
} 

public class Body 
{ 
    public IList<LineItem> LineItems { get; set; } 

    public Body() 
    { 
     LineItems = new List<LineItem>(); 
    } 
} 

public class LineItem 
{ 
    public string PartNumber { get; set; } 
    public string PartDescription { get; set; } 
    public int Quantity { get; set; } 
    public float ItemPrice { get; set; } 
    // computed 
    public float Total 
    { 
     get { return Quantity * ItemPrice; } 
    } 
} 

public class Footer 
{ 
    // populated via report.CalculateFooterTotals() 
    public int TotalItems { get; internal set; } 
    public float TotalPrice { get; internal set; } 
} 

일부 속성

는 물론 계산보다는 얻을/세트를 .

[편집]가

- 당신이이 질문 (DB 또는 다른 소스로부터 더 많은 것보다는 아마) 더글라스에게 물어 본대로, 사용의 비트를 추가하는 좋은 방법이 될 거라고 생각 :

// usage - set up report 
var report = new Report { 
    ReportUid = Guid.NewGuid().ToString(), 
    Header = 
    { 
     Name = "My new report", 
     Date = DateTime.UtcNow 
    }}; 
// add lineitems to body (in real case, probably a loop) 
report.Body.LineItems.Add(new LineItem() 
    { 
     Quantity = 1, 
     ItemPrice = 12.30f, 
     PartDescription = "New shoes", 
     PartNumber = "SHOE123" 
    }); 
report.Body.LineItems.Add(new LineItem() 
    { 
     Quantity = 3, 
     ItemPrice = 2.00f, 
     PartDescription = "Old shoes", 
     PartNumber = "SHOE999" 
    }); 
report.Body.LineItems.Add(new LineItem() 
    { 
     Quantity = 7, 
     ItemPrice = 0.25f, 
     PartDescription = "Classic Sox", 
     PartNumber = "SOX567" 
    }); 
// summerize the lineitems values in the footer 
report.CalculateFooterTotals(); 

그것은 보편적 주제 수요가있어 지금처럼 (HTML 등)이 확인 검사

private static void DispalyData(Report report) 
{ 
    // set out the basics 
    Console.WriteLine("Header"); 
    Console.WriteLine(report.ReportUid); 
    Console.WriteLine(report.Header.Date); 
    Console.WriteLine(report.Header.Name); 

    // now loop round the body items 
    Console.WriteLine("Items"); 
    foreach (var lineItem in report.Body.LineItems) 
    { 
     Console.WriteLine("New Item---"); 
     Console.WriteLine(lineItem.PartDescription); 
     Console.WriteLine(lineItem.Quantity); 
     Console.WriteLine(lineItem.ItemPrice); 
     Console.WriteLine(lineItem.PartNumber); 
     Console.WriteLine(lineItem.Total); 
     Console.WriteLine("End Item---"); 
    } 

    // display footer items 
    Console.WriteLine("Footer"); 
    Console.WriteLine(report.Footer.TotalItems); 
    Console.WriteLine(report.Footer.TotalPrice); 
} 

// called in code as: 
DispalyData(report); 

희망 캔버스 표면에 보고서를 적용 ... (편집을 통해) 커뮤니티 위키로 밀었다.

는 [BTW] - 당신이 vb.net의 변환기에 C#을 알고있을거야 altho, 나는이 일을 시도하고 꽤 유망한 같습니다 http://www.developerfusion.com/tools/convert/csharp-to-vb

+0

Jim에게 감사드립니다.이 질문은 귀하의 답변 사용법을 이해하고 실험하는 데 정말로 도움이됩니다. 내 실제 문제가 훨씬 더 복잡하지만,이 수업은 수업 시간과 반복 수업 시간에 내 두뇌를 갖게 해줍니다. 나는 일반적으로 수업에 대해 배울 수있는 것보다 더 많은 톤이 있다고 확신하지만, 이것은 나에게 갈 것이다. 나는 또 하나의 질문을한다. 어떻게 정의하고로드 할 것인가? 어떻게 출력 하는가? 콘솔에 표시합니다. – Jeff

+0

jeff ... 빠른 표시 부분을 추가하겠습니다 ... –

+0

환상적인 짐! ... 이것은 기본을 완벽하게 설명하고 다른 사람들을 도우 려합니다. 이 시간 내 주셔서 감사합니다. – Jeff

3

개체 유형마다 클래스를 만들어야합니다. 각자에게 자신의 파일을 제공하는 것이 가장 좋습니다.

Public Class Report 
    Public Property Header As Header 
    Public Property LineItems As IEnumerable(Of LineItem) 
    Public Property Footer As Footer 
End Class 


Public Class Header 
    Public Property Name As String 
    ' This probably isn't the best word choice because it is a type alias in VB 
    Public Property [Date] As Date 
End Class 


Public Class LineItem 
    Public Property PartNumber As Integer 
    Public Property PartDescription As String 
    Public Property NumberOfItems As Integer 
    Public Property PerItemPrice As Decimal 
    Public Property TotalPrice As Decimal 
End Class 


Public Class Footer 
    Public Property TotalItemsCount As Integer 
    Public Property TotalPrice As Decimal 
End Class 

과 같이 그것을 사용 :

Dim myReport As New Report() 
Dim myHeader As New Header() 
Dim lineItem1 As New LineItem() 
Dim lineItem2 As New LineItem() 
Dim myFooter As New Footer() 
With myReport 
    .Header = myHeader 
    .Footer = myFooter 
    .LineItems = {lineItem1, lineItem2} 
End With 
+0

감사합니다 더글러스 - 이걸 초기화하고 항목을 라인 아이템에 추가하는 방법을 보여줄 수 있습니까? – Jeff

+0

몇 가지 방법이 있습니다.각각에 대해 생성자를 만들고 거기에서 속성을 초기화하거나 기본 생성자를 사용하여 속성을 수동으로 설정할 수 있습니다. –

+0

또한'.Add' 메서드가 없으므로 항목을'IEnumerable'에 추가 할 수 없습니다. 당신이 그것을 추가하고 싶다면 그것을'ICollection'으로 변경할 필요가 있습니다. –

관련 문제