2011-03-31 3 views
0

매개 변수에 와일드 카드를 사용할 수 있습니까? TextLine1, TextLine2, TextLine3 및 TextLine 4 속성에 대해 반복되는이 코드가 있습니다. 번호를 와일드 카드로 바꿀 수 있으며 사용자 입력을 기반으로 숫자를 전달할 수 있습니까?개체에서 와일드 카드가 작동합니까?

TextLine1, TextLine2, TextLine3 및 TextLine 4는 ReportHeader 클래스의 속성입니다.

public Control returnTextLine(ReportHeader TextLineObj,int i) 
    { 

     System.Windows.Forms.Label lblTextLine = new System.Windows.Forms.Label(); 
     lblTextLine.Name = TextLineObj.**TextLine1**.Name; 
     lblTextLine.Font = TextLineObj.**TextLine1**.Font; 
     lblTextLine.ForeColor = TextLineObj.**TextLine1**.ForeColor; 
     lblTextLine.BackColor = TextLineObj.**TextLine1**.BackgroundColor; 
     lblTextLine.Text = TextLineObj.**TextLine1**.Text; 
     int x = TextLineObj.**TextLine1**.x; 
     int y = TextLineObj.**TextLine1**.y; 
     lblTextLine.Location = new Point(x, y); 


     return lblTextLine; 
    } 

제발 도와주세요

...

답변

5

아니요,이 작업을 수행 할 수 없습니다. ,

TextLineObj.TextLines[i].Name; 
+0

내가 공공 ReadOnlyCollection TextLines {얻을 "추가에 대한 정의가 포함되어 있지 않습니다"라는 {TextLine1, TextLine2, TextLine3, TextLine4}에서 또한 새로운 키워드에 오류가 발생하고있어, 개인 집합; } public ReportHeader() { TextLines = new ReadOnlyCollection {TextLine1, TextLine2}; } – NewBie

+0

@NewBie : 내 대답이 업데이트되었습니다. 다시 시도하십시오. –

2

짧은 답변 : 아니, 그것은 개체를 참조하는 와일드 카드를 사용할 수 없습니다.

대신 TextLine 인스턴스의 컬렉션을 ReportHeader에 저장해야합니다. 이렇게하면 인덱스별로 각 TextLine에 쉽게 액세스 할 수 있습니다.

public class ReportHeader 
{ 
    private TextLine[] textLines 

    ... 

    public TextLine[] TextLines 
    { 
     get { return this.textLines; } 
    } 

    ... 
} 

public Control returnTextLine(ReportHeader reportHeader, int textLineIndex) 
{ 
    TextLine textLine = reportHeader.TextLines[textLineIndex]; 

    System.Windows.Forms.Label lblTextLine = new System.Windows.Forms.Label(); 
    lblTextLine.Name = textLine.Name; 
    lblTextLine.Font = textLine.Font; 
    lblTextLine.ForeColor = textLine.ForeColor; 
    lblTextLine.BackColor = textLine.BackgroundColor; 
    lblTextLine.Text = textLine.Text; 
    int x = textLine.x; 
    int y = textLine.y; 
    lblTextLine.Location = new Point(x, y); 

    return lblTextLine; 
} 
1

그것은 반사 통해 수행 할 수 있습니다 :

public class TextLineObj 
{ 
    public ReadonlyCollection<TextLine> TextLines { get; private set; } 

    public TextLineObj() 
    { 
     TextLines = new ReadonlyCollection<TextLine>(
          new List<TextLine> { TextLine1, TextLine2, 
               TextLine3, TextLine4 }); 
    } 
} 

이런 식으로 사용 : 그러나 무엇을 할 수
ReadonlyCollection이 이는 TextLines 속성 TextLineObj을 나타내는 클래스를 확장하는 것입니다 당연하지. 그러나 Daniel이 제안한 솔루션을 사용하는 것이 좋습니다.

관련 문제