2011-03-31 42 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提出的解决方案。

相关问题