|
发表于 2019-4-30 00:04:22
|
显示全部楼层
江苏省扬州市
本帖最后由 qingshanlushui 于 2019-4-30 00:08 编辑
发现语法糖:this(name,age)。。。
static void Main(string[] args)
{
Type t = typeof(Person);
//无参数的Person
ConstructorInfo p1 = t.GetConstructor(new Type[0]);
Person person1 = p1.Invoke(new object[0]) as Person;
FieldInfo f1 = t.GetField("test");
f1.SetValue(person1, "settest");
Console.WriteLine(f1.GetValue(person1));
FieldInfo f2 = t.GetField("text");
f2.SetValue(person1, "settext");
Console.WriteLine(f2.GetValue(person1));
PropertyInfo f3 = t.GetProperty("Name");
f3.SetValue(person1, "setName");
Console.WriteLine(f3.GetValue(person1));
PropertyInfo f4 = t.GetProperty("Address");
f4.SetValue(person1, "setAddress");
Console.WriteLine(f4.GetValue(person1));
PropertyInfo f5 = t.GetProperty("Age");
f5.SetValue(person1, 11);
Console.WriteLine(f5.GetValue(person1));
MethodInfo m1 = t.GetMethod("SayHi", new Type[0]);
m1.Invoke(person1, new Object[0]);
MethodInfo m2 = t.GetMethod("SayHi", new Type[] { typeof(string)});
m2.Invoke(person1, new Object[1]);
MethodInfo m3 = t.GetMethod("SayHi", new Type[] { typeof(string), typeof(int) });
m3.Invoke(person1, new Object[2]);
//有参数的Person以及SayHi
ConstructorInfo p2 = t.GetConstructor(new Type[] { typeof(string), typeof(int) });
Person person2 = p2.Invoke(new object[] { "name2", 12 }) as Person;
MethodInfo m4 = t.GetMethod("SayHi", new Type[0]);
m1.Invoke(person2, new Object[0]);
ConstructorInfo p3 = t.GetConstructor(new Type[] { typeof(string), typeof(string) });
Person person3 = p3.Invoke(new object[] { "name3", "address3" }) as Person;
m2.Invoke(person3, new Object[1]);
ConstructorInfo p4 = t.GetConstructor(new Type[] { typeof(string), typeof(int), typeof(string) });
Person person4 = p4.Invoke(new object[] { "name4", 17, "address4" }) as Person;
m3.Invoke(person4, new Object[2]);
Console.Read();
}
控制台结果:
settest
settext
setName
setAddress
11
大家好,我的名字叫setName
大家好,我的名字叫setName
大家好,我的名字叫setName
大家好,我的名字叫name2
大家好,我的名字叫name3
大家好,我的名字叫name4
|
|