namespace 反射
{
class Person
{
//一 数据成员(字段)
private int id;
public string name;
public int age;
protected double money;
//属性
public int ID
{
get { return id; }
set { id = value; }
}
public double Money
{
get { return money; }
set { money = value; }
}
//二 函数成员
public void study()
{
}
public void sleep()
{
}
private void play()
{
}
protected void move()
{
}
}
class Program
{
static void Main(string[] args)
{
//获取某种类型的type对象
//1、通过对象中调用函数GetType
Person p1 = new Person();
Person p2 = new Person();
Type tpPerson1 = p1.GetType();
Type tpPerson2 = p2.GetType();
//两个type对象比较(所有的Person对象共享)
if(tpPerson1.Equals(tpPerson2))
{
Console.WriteLine("tpPerson1== tpPerson2");
}
//两个Person对象比较(两个独立的内存)
if(p1.Equals(p2))
{
Console.WriteLine("p1== p2");
}
else
{
Console.WriteLine("p1!= p2");
}
//2、通过typeof运算符获取
Type tpPerson = typeof(Person);
//获取数据类型的名字
string className = tpPerson.Name;
Console.WriteLine("类型名字="+className);
//获取类型所在的命名空间
string nmSpace= tpPerson.Namespace;
Console.WriteLine("命名空间=" + nmSpace);
//获取类型所在的程序集名字
Assembly assembly = tpPerson.Assembly;
Console.WriteLine("程序集名字=" + assembly);
//获取类中共有的字段(共有数据成员)
Console.WriteLine("获取类中所有的公有字段");
FieldInfo[] fieldInfos = tpPerson.GetFields();
foreach (FieldInfo item in fieldInfos)
{
Console.WriteLine(item);
}
Console.WriteLine("获取类中所有的公有属性");
PropertyInfo[] propertyInfos = tpPerson.GetProperties();
foreach (PropertyInfo item in propertyInfos)
{
Console.WriteLine(item);
}
Console.WriteLine("获取类中所有的公有函数");
MethodInfo[] methodInfos = tpPerson.GetMethods();
foreach (MethodInfo item in methodInfos)
{
Console.WriteLine(item);
}
Console.WriteLine("获取类中所有的公有成员(数据和函数)");
MemberInfo[] memberInfos = tpPerson.GetMembers();
foreach (MemberInfo item in memberInfos)
{
Console.WriteLine(item);
}
Console.WriteLine("获取类中所有的非公有成员(数据和函数)");
MemberInfo[] memberInfosNoPublic= tpPerson.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MemberInfo item in memberInfosNoPublic)
{
Console.WriteLine(item);
}
Console.ReadKey();
c#--反射
最新推荐文章于 2024-04-19 15:52:09 发布