c# - 如何将字符串转换为控件和方法?
问题描述
我想串一个控制方法的输出;这是我的代码,但它不起作用;
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");
非常感谢您提前
解决方案
由于“文本”是 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");
推荐阅读
- javascript - 说店铺是模特对吗?
- html - 如何制作连接到数据库的html登录页面
- python - 获取 pandas 布尔系列为 True 的索引列表
- c# - 使用自定义表数据类型执行存储过程
- asp.net-core - 使用 .NET Core 2.1 实现 Google Open ID Connect 的正确方法是什么?
- javascript - 函数中的异步,等待第一个函数完成,然后再触发下一个函数
- git - 无法从 origin/ 提交文件
到原点/主 - node.js - 带有 Socket.io 和 Express 的 Node.js 聊天应用程序在本地工作,但不在主机上
- android - Android Camera2 onCaptureStarted 回调
- azure-ad-b2c - B2C重置密码