返回顶部

反射实例

实例

StudentInfo
public class StudentInfo
    {
        public StudentInfo()
        {

        }
        public StudentInfo(string nickName)
        {
            _nickName = nickName;
        }

        public StudentInfo(int age)
        {
            Age = age;
        }


        private string _nickName = "张三";

        private bool _isfriend = true;

        public bool IsFriend
        {
            get { return _isfriend; }
            set { _isfriend = value; }
        }


        public int Age { get; set; }

        public string NickName
        {
            get
            {
                if (_isfriend)
                {
                    return _nickName;
                }
                else
                {
                    return "任我行";
                }
            }
            set { _nickName = value; }
        }

        /*
         * ToString,GetHashCode,GetType(),Equeal
         */

        public void Run()
        {
            Console.WriteLine($"{_nickName}我正在跑步...");
        }
    }
Console.WriteLine("************获取所有属性************");
                //获取类型
                Type t = typeof(StudentInfo);
                var props = t.GetProperties();
                foreach (var propertyInfo in props)
                {
                    Console.WriteLine(propertyInfo.Name);
                }

效果:

Console.WriteLine("\r\n************获取所有方法************\r\n");
                /*
                 * 1.获取类型
                 * 2.GetMethods()
                 * 3.不包含构造方法
                 */
                var t = typeof(StudentInfo);
                var methods = t.GetMethods();
                foreach (var methodInfo in methods)
                {
                    Console.WriteLine(methodInfo.Name);
                }

                Console.WriteLine(methods.Length);

Console.WriteLine("\r\n************获取类型名称************\r\n");
                var t = typeof(StudentInfo);
                Console.WriteLine(t.Name);
                Console.WriteLine(t.FullName);//包含命名空间

Console.WriteLine("\r\n************获取字段************\r\n");
                var t = typeof(StudentInfo);
                var fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (var fieldInfo in fields)
                {
                    Console.WriteLine(fieldInfo.Name);
                }

Console.WriteLine("\r\n************调用构造函数************\r\n");
                var t = typeof(StudentInfo);
                Type[] types = new Type[1];
                types[0] = typeof(string);//表示要获取参数类型为String的构造函数
                var cons = t.GetConstructor(types);
                //调用构造函数,并给构造传递参数值
                var student = cons.Invoke(new object[] { "任我行" }) as StudentInfo;
                Console.WriteLine(student.NickName);

Console.WriteLine("\r\n************调用方法************\r\n");
                /*
                 * 1.获取类型
                 * 2.创建对象
                 * 3.调用方法
                 */
                var t = typeof(StudentInfo);
                object obj = Activator.CreateInstance(t, 999);
                var methodInfo = t.GetMethod("Run"); //获取需要调用的方法名称
                methodInfo.Invoke(obj, null);//调用Run方法,指定方法在哪个对象下被调用,null参数表示此方法是无参方法

Singleton

 

public class Singleton
    {
        private string _nickName;
        public Singleton(string nickName)
        {
            _nickName = nickName;
        }

        public string NickName => _nickName;

        private void Run()
        {
            Console.WriteLine($"我是{_nickName},这是私有跑步方法");
        }
    }

 

Console.WriteLine("\r\n************调用私有方法************\r\n");
                //黑科技
                var t = typeof(Singleton);
                var obj = Activator.CreateInstance(t, "天道无情");
                var methodInfo = t.GetMethod("Run", BindingFlags.NonPublic | BindingFlags.Instance); //获取需要调用的方法名称
                methodInfo.Invoke(obj, null);//调用私有方法

Console.WriteLine("\r\n************加载程序集************\r\n");
                Assembly assembly = Assembly.Load("反射");
                Type t = assembly.GetType("反射.StudentInfo");
                var obj = Activator.CreateInstance(t, "天道无情");

                var methodInfo = t.GetMethod("Run");
                methodInfo.Invoke(obj, null);//调用

Console.WriteLine("\r\n************反射给属性赋值************\r\n");
                var t = typeof(StudentInfo);
                object obj = Activator.CreateInstance(t, 999);//创建对象
                var p = t.GetProperty("NickName");

                p.SetValue(obj, "范涛涛");//设置指定对象obj属性值
                var val = p.GetValue(obj);//获取指定对象obj属性值
                Console.WriteLine(val);

配置文件中添加

<connectionStrings>
    <add name="Default" connectionString="server=127.0.0.1;database=WeekCodeFirst;uid=test1608;pwd=123456" providerName="System.Data.SqlClient"/>
  </connectionStrings>
public class DbHelper<T>
    {
        private static readonly string _connString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
        //新增
        public int Insert(T model)
        {
            int result = 0;
            var t = typeof(T);
            using (SqlConnection conn = new SqlConnection(_connString))
            {
                conn.Open();
                string strSql = "insert into 表名(字段1,字段2,字段3) values(@字段1,@字段2,@字段3)";
                StringBuilder sql = new StringBuilder();//用于字符串拼接的类
                sql.Append($"Insert into {t.Name}(");
                var props = t.GetProperties().ToList();
                props.RemoveAt(0);//移除了主键
                var names = props.Select(p => p.Name).ToList();
                sql.Append(string.Join(",", names));//将类型的所有属性用","号隔开,如:属性1,属性2....
                sql.Append($") values(@{string.Join(",@", names)})");
                result= conn.Execute(sql.ToString(),model);
            }
            return result;
        }
    }

CourseInfo

public class CourseInfo
    {
        public int Id { get; set; }
        public string CourseName { get; set; }
        public int TeacherId { get; set; }

    }
Console.WriteLine("\r\n************反射抽象添加数据************\r\n");
                DbHelper<CourseInfo> helper = new DbHelper<CourseInfo>();
                CourseInfo info = new CourseInfo()
                {
                    Id = 899,
                    CourseName = "C#高级开发",
                    TeacherId = 22
                };
                helper.Insert(info);
posted @ 2019-04-02 16:23  世界欠绘梨衣一场婚礼  阅读(185)  评论(0编辑  收藏  举报