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()的运行
在这里插入图片描述
成员变量的名字(开头都是大写)+返回的值

转载请联系

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值