【发布时间】:2015-09-26 21:43:25
【问题描述】:
我不确定这在 C# 中是否容易实现。但我想知道如何轻松做到这一点。
public partial class Form1
{
// I left out the unimportant code for this example
private myControl cLeft,cTop,cBottom,cRight;
private List<myControl>mControls;
public Form1()
{
InitializeComponents();
//this list should contain the fields cLeft,cTop,cBottom,cRight...
mControls=new List<myControl>(){cLeft,cTop,cBottom,cRight};
/* now I want that cLeft and so on get assigned...
of course, this doesn't work because the list refers to the values of
cLeft ... which are null. So I would need to store a reference to those fields to get this work.*/
mControls.ForEach(x=>x=new myControl(this));
}
}
我确信它可以通过反射来完成,但我认为应该有一种方法可以在 C# 中轻松做到这一点,还是不可能?
【问题讨论】:
-
这是不可能的,即使有反射。你必须用
unsafe做一些诡计来实现这一点。这样做也是一个真的坏主意,你应该重新考虑你想要实现的目标。通过似乎与变量无关的代码在背后更改变量是不可调试代码库的秘诀。 -
@GrantWinney myControl 在设计器中不存在。这个问题不是询问创建控件,而是询问引用字段
-
@singsuyash 不相似。我想通过迭代“引用”列表来设置变量 cLeft 等等
-
请注意,我将您的问题标记为欺骗,因为其他人实际上正在尝试您想要实现的目标。
params with ref。好主意,但不可能。
标签: c#