2011-03-31 43 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

不,這是做不到的。
但是你可以做什麼,是一個TextLines屬性擴展代表TextLineObj的類,這是一個ReadonlyCollection

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

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

使用方法如下:

TextLineObj.TextLines[i].Name; 
+0

我在新的關鍵字得到的錯誤,並在{TextLine1,TextLine2,TextLine3,TextLine4}說「不包含定義添加」 公共ReadOnlyCollection 的TextLine {獲得;私人設置; } public ReportHeader() { TextLines = new ReadOnlyCollection {TextLine1,TextLine2}; } – NewBie 2011-03-31 12:38:20

+0

@NewBie:更新了我的答案。再試一次。 – 2011-03-31 12:41:29

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

它可以通過反射來完成,當然。但我建議使用Daniel提出的解決方案。

相關問題