开发者

C# Replacement for macro?

I'm trying to define 10 panels in my code, but absolutely do not want to do

public panel1();
public panel2();
etc....

and a quick google search tells me macros are not available in c#. Is there some kind开发者_如何学编程 of array I can define to use in place of a macro, or some other way I could handle this ?


Your question is not too clear; but this is how you would define an array of Panels in C#:

Panel[] panels = new Panel[10];

You can use an initializer expression to fill in the panels:

Panel[] panels = new Panel[] { new Panel(), new Panel(), /* ... */ };

It is more likely that you want to loop over something and have some logic create the array - perhaps in a loop or as a LINQ expression, for instance:

Panel[] panels = Enumerable.Range(0,10).Select(n => new Panel(n)).ToArray();


Why not just use a for loop and add them dynamically with a few lines? Something like this:

for (int i=0;i<10;i++)
{
    Panel newPanel = new Panel();
    // each time through there is a new panel to use
}


I would use a generic list and the for loop mentioned above like this:

List<Panel> list = new List<Panel>();
for (int i = 0; i < 10; i++)
{
    list.Add(new Panel());
}


If you just want 10 of something, then you don't want your expression cluttered with loops or other irrelevant constructs.

I suggest using:

var panels = 10.Of<Panel>();

... which can be achieved with the following extension method:

public static T[] Of<T>(this int number) where T : new()
{
  var items = new List<T>();
  for (int i = 0; i < number; i ++)
  {
    items.Add(new T());
  }
  return items.ToArray();
}

That will keep the intent of your code much clearer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜