Will wildcards work on objects?
Is it possible to use wild cards in a parameter? I have this code which repeats for the properties TextLine1,TextLine2, TextLine3, and TextLine 4. Is it possible to replace the number with a wildcard and so that i can pass the number based on user input.
TextLine1, TextLine2, TextLine3, and TextLine 4 are properties of the class 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.**TextLin开发者_开发知识库e1**.BackgroundColor;
lblTextLine.Text = TextLineObj.**TextLine1**.Text;
int x = TextLineObj.**TextLine1**.x;
int y = TextLineObj.**TextLine1**.y;
lblTextLine.Location = new Point(x, y);
return lblTextLine;
}
Please Help...
No, this can't be done.
What you can do however, is to extend the class representing TextLineObj
with a TextLines
property which is a ReadonlyCollection
:
public class TextLineObj
{
public ReadonlyCollection<TextLine> TextLines { get; private set; }
public TextLineObj()
{
TextLines = new ReadonlyCollection<TextLine>(
new List<TextLine> { TextLine1, TextLine2,
TextLine3, TextLine4 });
}
}
Use it like this:
TextLineObj.TextLines[i].Name;
Short answer: No, it's not possible to use wildcards for referencing objects.
You should instead store a collection of the TextLine
instances in ReportHeader
. This way you can easily access each TextLine by index.
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;
}
It could be done via reflection, of course. But I suggest to use the solution proposed by Daniel.
精彩评论