乐趣区

关于后端:C使用反射访问对象属性方法

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.ComponentModel;
usingSystem.Linq;
usingSystem.Reflection;
publicclassreflectModel
{
publicstaticvoidTestShowReflect()
{
// 反射读取类公有属性
Personper=newPerson(“ismallboy”,”20102100104″);
Typet=per.GetType();
// 获取公有办法
MethodInfomethod=t.GetMethod(“GetStuInfo”,BindingFlags.NonPublic|BindingFlags.Instance);
// 拜访无参数公有办法
stringstrTest=method.Invoke(per,null).ToString();C# 应用反射拜访对象属性办法
// 拜访有参数公有办法
MethodInfomethod2=t.GetMethod(“GetValue”,BindingFlags.NonPublic|BindingFlags.Instance);
object[]par=newobject[2];
par[0]=”ismallboy”;
par[1]=2;
stringstrTest2=method2.Invoke(per,par).ToString();
// 获取公有字段
PropertyInfofield=t.GetProperty(“Name”,BindingFlags.NonPublic|BindingFlags.Instance);
// 拜访公有字段值
stringvalue=field.GetValue(per).ToString();
// 设置公有字段值
field.SetValue(per,”newName”);
value=field.GetValue(per).ToString();
}
}
///<summary>
/// 个人信息
///</summary>
classPerson
{
privatestringName{get;set;}
privatestringStuNo{get;set;}
publicPerson(stringname,stringstuNo)
{
this.Name=name;
this.StuNo=stuNo;
}
privatestringGetStuInfo()
{
returnthis.Name;
}
privatestringGetValue(stringstr,intn)
{
returnstr+n.ToString();
}
}
reflectModel

退出移动版