C#之type反射
创建学生类
运用type进行反射
讲解
下面展示一些 内联代码片
。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
namespace 第六周作业反射之Type
{
class Student
{
Student() { }
public string name;
public string Sno;
public string major;
public Student(string name, int age, string Sno, string major)
{
this.name = name;
this.age = age;
this.Sno = Sno;
this.major = major;
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public string Major
{
get { return this.major; }
set { this.major = value; }
}
public string SNO
{
get { return this.Sno; }
set { this.major = value; }
}
private int age;
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public void Sayhi()
{
Console.WriteLine("大家好,我是 " + this.name + " 来自 " + this.major + " 学号:" + this.Sno);
}
}
class Program
{
static void Main(string[] args)
{
Student st = new Student("The Shy",17,"1717070027","上单");
Type t1 = st.GetType();
Console.WriteLine(t1.FullName);
//识别构造函数
ConstructorInfo[] con = t1.GetConstructors();
foreach(ConstructorInfo c in con)
{
Console.WriteLine(c.ToString());
}
查看类中属性
//PropertyInfo[] pi = t1.GetProperties();
//foreach(PropertyInfo p in pi)
//{
// Console.WriteLine(p.Name+": "+p.GetValue(st));
//}
FieldInfo[] fi = t1.GetFields();
//取得字段
//输出成员变量的值Fieldinfo指的是成员变量,不能取得private属性的值
foreach (FieldInfo i in fi)
{
Console.WriteLine(i.Name + ": " + i.GetValue(st));
}
Console.ReadKey();
}
}
}
记录学习片段
GetFields是专门去得到成员变量,并不会去拿成员函数
相对地GetProperties()是专门去得到成员函数,不会去拿成员变量
下面是运行properties的照片
成员函数的名字(开头都是大写)+返回的值
下面是GetFields()的运行
成员变量的名字(开头都是大写)+返回的值
转载请联系