【问题标题】:How can I convert String to Controls and Methods?如何将字符串转换为控件和方法?
【发布时间】:2021-10-01 06:48:56
【问题描述】:

我想把一个控制方法的输出串起来; 这是我的代码,但它不起作用;

        public static string get(string control_name, string method)
        {
            string result = "null";
            foreach (var control_ in Controls) //Foreach a list of contrls
            {
                if ((string)control_.Name == (string)control_name) //Find the control
                {
                    try
                    {
                        Type type = control_.GetType();
                        MethodInfo method_ = type.GetMethod(method);
                        result = (string)method_.Invoke(method, null); 
//Ejecuting and savind the output of the method on a string
                    }
                    catch (Exception EXCEPINFO)
                    {
                        Console.WriteLine(EXCEPINFO);
                    }
                }
            }
            return result;
        }

调用函数:

    form.Text = get("button_1", "Text");

非常感谢您

【问题讨论】:

  • 文本是一个属性。所以你不需要GetMethod,而是GetProperty
  • MethodInfo.Invoke的第一个参数是你调用方法的对象,所以这里control_

标签: c# list winforms methods controls


【解决方案1】:

由于“文本”是 WinForm 中某些控件的属性,而不是方法,因此您需要引用 GetProperty(或将 InvokeMember 与 GetProperty 绑定一起使用)才能读取其中一个值。

我认为下面的代码应该可以工作(但未经测试)。

顺便说一句,我不会将方法称为“get”,因为它是 C# 关键字。

    public static string GetControlPropertyValue(string control_name, string propertyName) {
            string result = null;
            Control ctrl= Controls.FirstOrDefault( c => (c as Control)?.Name == control_name)
            if (ctrl != null) {
                try {
                    var resultRaw = ctrl.GetType().InvokeMember(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, ctrl, null);
                    result = resultRaw as string;
                }
                catch (Exception ex) {
                    Console.WriteLine(ex);
                }
            }
            return result;
        }

    //invocation
    var text = GetControlPropertyValue("button_1", "Text");

【讨论】:

  • var ctl = Controls.Find("[Control Name]", true).FirstOrDefault(); string value = ctl?.GetType().GetProperty("[Property Name]").GetValue(ctl).ToString();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多