Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#替换宏?_C#_Macros - Fatal编程技术网

C#替换宏?

C#替换宏?,c#,macros,C#,Macros,我试图在代码中定义10个面板,但绝对不想这样做 public panel1(); public panel2(); etc.... 快速的谷歌搜索告诉我宏在c#中是不可用的。我可以定义某种数组来代替宏,或者用其他方法来处理这个问题吗?为什么不使用for循环并用几行动态添加它们?大概是这样的: for (int i=0;i<10;i++) { Panel newPanel = new Panel(); // each time through there is a new

我试图在代码中定义10个面板,但绝对不想这样做

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

快速的谷歌搜索告诉我宏在c#中是不可用的。我可以定义某种数组来代替宏,或者用其他方法来处理这个问题吗?

为什么不使用
for
循环并用几行动态添加它们?大概是这样的:

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

for(int i=0;i您的问题不太清楚;但这就是在C#中定义面板数组的方式:

可以使用初始值设定项表达式填充面板:

Panel[] panels = new Panel[] { new Panel(), new Panel(), /* ... */ };
更可能的情况是,您希望在某个对象上循环,并让某些逻辑创建数组-可能是在循环中或作为LINQ表达式,例如:

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

我将使用一个通用列表和上面提到的for循环,如下所示:

for (int i=0;i<10;i++)
{
    Panel newPanel = new Panel();
    // each time through there is a new panel to use
}
List<Panel> list = new List<Panel>();
for (int i = 0; i < 10; i++)
{
    list.Add(new Panel());
}
List List=新列表();
对于(int i=0;i<10;i++)
{
添加(新面板());
}

如果您只需要10个,那么您不希望表达式中充斥着循环或其他不相关的结构

我建议使用:

var panels = 10.Of<Panel>();
var panels=10.Of();
…可通过以下扩展方法实现:

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();
}
public static T[]Of(此整数),其中T:new()
{
var items=新列表();
for(int i=0;i

这将使代码的意图更加清晰。

为什么/如何使用宏?当然可以(也应该)使用数组。C宏不会让冗余变量变得更容易接受,只是稍微更容易处理。我认为他指的不是C宏——我想他指的是Lisp。为什么有人需要宏来做任何事情?@manojlds假设你不使用trolling,这里有一个很好的讨论:如果你使用初始值设定项表达式,它们都是一样的(如您的示例所示)或类似的(如1、2、3…)我建议执行
Panel[]panels=newpanel[10];
然后使用for循环来初始化值。更简洁。@Tim S:但是在代码中使用循环或LINQ语句会损害可读性。如果您只想构造10个某物,那么代码越接近“给我10个某物”,您的意图就越清晰。