反射由浅入深了解学习(二)

反射由浅入深了解学习(一)

 一,反射对实体的操作,如下代码:

UserModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class UserModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string title;
    }
}
Program
using Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 实体
            Type type = typeof(UserModel);
            object obj = Activator.CreateInstance(type);
            ///遍历获取对象属性和自动赋值
            foreach (var item in type.GetProperties())
            {
                if (item.Name.Equals("Id"))
                {
                    item.SetValue(obj, 12);
                }
                if (item.Name.Equals("Name"))
                {
                    item.SetValue(obj, "Name");
                }
                Console.WriteLine("属性名--{0},值--{1}", item.Name, item.GetValue(obj));
            }
            foreach (var item in type.GetFields())
            {
                if (item.Name.Equals("title"))
                {
                    item.SetValue(obj, "title");
                }
                Console.WriteLine("字段名--{0},值--{1}", item.Name, item.GetValue(obj));
            }
            #endregion

            Console.ReadKey();
        }
    }
}

 输出结果:

二,实体反射的扩展(orm返回实体)

1,动态生成SQL数据库语句,orm反射返回实体核心思想,如下代码

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionDemo
{
    public class DbHepler
    {

        private static string conStr = ConfigurationManager.AppSettings["DbCon"]; //用的是sql数据库,数据库链接
        public static T Query<T>(int id)
        {
            Type type = typeof(T);
            foreach (var item in type.GetProperties())
            {
                ///输出属性名
                Console.WriteLine("属性名--{0}", item.Name);
            }

            //通过属性名凭借数据库列
            string colums = string.Join(",", type.GetProperties().Select(m => $"[{m.Name}]"));
            string sql = $"select {colums} from {type.Name}  where id=@id";
            IEnumerable<SqlParameter> parameters = new List<SqlParameter>()
            {
                new SqlParameter("@id",id),
            };

            using (SqlConnection con = new SqlConnection(conStr))
            {
                SqlCommand sqlCommand = new SqlCommand(sql, con);
                sqlCommand.Parameters.AddRange(parameters.ToArray());
                con.Open();
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
                //判断是否为空,为空就返回默认类型
                if (sqlDataReader.Read())
                {
                    ///根据类型创建实例
                    T t = (T)Activator.CreateInstance(type);
                    foreach (var item in type.GetProperties())
                    {
                        //根据属性给实例赋值
                        item.SetValue(t, sqlDataReader[item.Name]);
                    }
                    ///返回创建的实例
                    return t;
                }
                else
                {
                    return default(T);
                }
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/May-day/p/10868375.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值