如何解决如何将字符串转换为控件和方法?
我想把一个控制方法的输出串起来; 这是我的代码,但它不起作用;
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");
非常感谢您提前
解决方法
由于“Text”是 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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。