简体   繁体   English

将控件的属性名称传递给函数

[英]Pass property name of controls to a function

I have function that changes the property of controls based on the control name and the input command. 我具有根据控件名称和输入命令更改控件属性的功能。

 public void SetControl(string ControlName, string Operation)
    {
        Control Control = this.Controls.Find(ControlName, true)[0];

        switch (Operation)
        {
            case "ok":
                Control.BackColor = Color.Green;
                Control.ForeColor = Color.Black;
                break;
            case "error":
                Control.BackColor = Color.Red;
                Control.ForeColor = Color.Blue;
                break;
        }
    }

now I am wondering if there is any way to pass property name as well? 现在我想知道是否还有任何方法可以传递属性名称? of course I can do something like this: 我当然可以做这样的事情:

if (propertyname=="ForeColor")
 {Control.ForeColor = Color.Black;}

but then I should do this for all of the properties that I am going to change! 但是我应该对所有要更改的属性执行此操作! Is there anyway to find and change the property based on its name? 无论如何,是否有根据其名称查找和更改属性的信息?

Yes. 是。 This is precisely what reflection does. 这正是反射的作用。

var value = Control.GetType().GetProperty(propertyname).GetValue(Control, null);

Then set your value 然后设定你的价值

Control.GetType().GetProperty(propertyname).SetValue(Control, valueToSet);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM