1,根据字段名和具体对象,获取对象的属性的值
/// <summary>
/// 根据字段名和具体对象,获取对象的属性的值
/// </summary>
/// <param name="FieldName">字段名</param>
/// <param name="obj">具体的对象</param>
/// <returns></returns>
public string GetModelValue(string FieldName, object obj)
{
try
{
Type Ts = obj.GetType();
object o = Ts.GetProperty(FieldName).GetValue(obj, null);
string Value = Convert.ToString(o);
if (string.IsNullOrEmpty(Value)) return null;
return Value;
}
catch
{
return null;
}
}
应用代码
//根据input的值,检测IO输入是否有值
//if (this.txt_input.Text == "6")//不用反射的话,要写太多的代码啦。有DI_6,DI_5......
//{
// if (Global.myAdam6250.DI_6 == "True")
// {
// Flag_Tighten_Done = true;
// }
//}
string fieldName = "DI_" + this.txt_input.Text;
string strInputValue = GetModelValue(fieldName, Global.myAdam6250);//根据属性的名称字符串,获取属性值
if (strInputValue == "True")//如果有输入
{
Flag_Tighten_Done = true;//执行完成
if (IsSetOut == true)
{
GetAndExecuteMethod(frmMonitor, methodName, null);//改变输出的状态
IsSetOut = false;
}
}
2,根据具体的对象和方法名,调用方法
/// <summary>
/// 根据具体的对象和方法名,调用方法
/// </summary>
/// <param name="objClass">对象</param>
/// <param name="methodName">需要调用的方法名</param>
/// <param name="parameters">传递的参数值</param>
public void GetAndExecuteMethod(object objClass, string methodName, object[] parameters = null)
{
try
{
Type t = objClass.GetType();
//获取对象的公共方法
MethodInfo mi = t.GetMethod(methodName);
//object objinstance = Activator.CreateInstance(t);//这里是调用另外一个已经打开的窗体的方法,所以不能在创建实例
//执行方法
mi.Invoke(objClass, parameters);
}
catch (Exception)
{
throw;
}
}
应用代码:
//给IO输出信号,取料灯点亮
string methodName = "SetOut_" + this.txt_output.Text;
if (StringHelper.IsInteger(this.txt_output.Text))//如果是数字
{
//frmMonitor.Out_4();//调用已经打开窗体的公共方法,不用反射的话只能写死方法
if (IsSetOut == false)
{
GetAndExecuteMethod(frmMonitor, methodName, null);//根据方法名,调用方法,frmMonitor是一个窗体的实例
IsSetOut = true;
}
}
原文:https://www.cnblogs.com/baozi789654/p/13752273.html