C# 反射的例子

时间:2023-03-10 06:52:55
C# 反射的例子

通过字符串变量访问控件

string t = "textbox1";
TextBox tb = (TextBox)this.GetType().GetField(t, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this);
tb.text="成功";

通过字符串变量访问对象属性值

//获取x的类型
Type t = x.GetType();
//通过变量"type"访问x的类型的属性变量typeStr的属性信息(propertyInfo)
System.Reflection.PropertyInfo propertyInfo = t.GetProperty(typeStr);
//通过属性信息,使用对象实例赋值。
propertyInfo.SetValue(x, "成功", null);
//利用反射。获取并执行传入方法,
MethodInfo methods = this.GetType().GetMethod(method);
if (methods != null)
{
methods.Invoke(this, new object[] { });
}