将控件存储在变量中
我想将通用控件存储在变量中而不知道其类型。我需要访问一些常见属性,例如名称、大小、位置...我只想存储单选按钮、标签、图片框...任何人都可以告诉我如何执行此操作吗?
I want store generic controls in variable without knowing its type. By I need access to some of common properties such as name, size, location... i want to only store radio buttons, labels,picture box... can anyone give me any idea how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,您可以使用
List; myControls = new List();
虽然 Control 是每个 WinForm Control 的基类,但您可以访问诸如 Name 之类的属性。
您还可以通过执行以下操作将强制转换为控制
Yes you can using
List<Control> myControls = new List<Control>();
while Control is baseclass of each WinForm Control you can access Properties like Name .
Than you can also backward the Cast to Control by doing
如果您谈论的是 Winform,它们都派生自 Control,因此只需创建一个 Control 列表,如下所示:
If you are talking about Winforms, they all derive from Control, so just make a list of Controls like this:
控件继承自基类
Control
,它具有您提到的所有属性。您可以键入控件集合来包含Control
。Controls inherit from the base class
Control
, and it has all the properties you mention. You could type your collection of controls to containControl
.将变量声明为所有这些控件继承的类型的列表,我认为该类型是
Control
。然后,您可以访问Control
类声明的所有成员(包括属性)。Declare the variable as a list of the type that all those controls inherit from, which i believe would be
Control
. You can then access all the members (including properties) that are declared by theControl
class.你可以这样做:
You can do it that way:
声明一个基类类型的变量。作为基类类型变量可以保存子类的实例。
例如,在 WPF 中,您可以执行
List
对于 Win Forms,您可以执行
List
Declare a variable of Base class type. As base class type variable can hold instances of child classes.
For example in WPF you can do
List<System.Windows.Controls.Control>
for Win Forms you can do
List<System.Windows.Forms.Control>