C#基础--attribute||reflect

来源:互联网 发布:算法伪代码怎么写 编辑:程序博客网 时间:2024/06/15 12:42

注: 本文是给有2天以上C#基础的人看的

先提出一个问题:完成一个功能,给你任意一个实体,插入表中。注意,在客户端不要出现sql语句。(参考hibernate只需要少量的配置,你就可以建立实体与数据库中表的 关系)问题的关键就是如何建立实体与表的关系。

面向对象语言里都有一个机制–reflect(反射),反射的作用动态获取类,对应对象的属性,获取实例(官方定义:)这样你就可以动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。
就本问题来看,解决方法出来了
(以下代码没有验证)
1.设置表–表名和主键名。可以将主键单独列出

Class TableAttribute:System.Attribute{    private string _tableName;    private string _pk;    public string     public string TableName{get=>_tableName;set=>_tableName=value;}    public string PK{get=>_pk;set=>_pk=value;}    public TableAttribute(string _tableName){        this._tabbleName=_tableName;}}

2.设置字段

Class FildAttribute:System.Attribute{    private string _rowName;    private string _rowTpye;    private int _length;    private string message;    public string RowName{get=>_rowName;set=>_rowName=value;}    public string RowType{get=>_rowTpye;set=>_rowType=value;}    public int Length{get=>_length;set=>_length=value;}    public FildAttribute(string _rowName,string _rowType,int length){        this._rowName=_rowName;        this._rowType=_rowType;        this._length=_length;    }}

3.设置实体–这里的表名,主键名,属性名一定要和数据库里面相同。

[Table(TableName,pk)]Class Entity{    private int _param1;    private string _param2;    .    .    .    [Fild(RowName,RowType,Length,message="我是构造函数中没有的属性,用来描述")]    public int Param1{get=>_param1;set=>_param1=value;}    .    .    .}

我建议写一个配置文件,二来写sqlHpler类,配置文件用来链接需要的数据库,sqlHpler用来链接数据库,单例模式创建一个SqlConnection对象,封装对数据库的操作。在使用的程序中,对于数据库只需要这么一句代码
var conn = SqlHpler.Instance.GetConnection()就可以链接数据库。
稍后我会把代码p上
4.接下来该操作这些东西了

Entity entityType type = typeof(entity);

获取表名—-具体函数名字记不清了

var infos = type.GetCustomAttributes(typrof(TableAttribute),false);string tableName = ((TableAttribute)infos[0]).TableName;

主键名同理
字段名–字段值

var infos = type.GetProperties();foreach(var info in infos){    if(null!=info){    object[] objects = info.GetCustomAttribute(typeof(FildAttribute),false);        foreacn(var obj in objects){            string propName = ((FildAttribute)obj).RowName;            String propValue = type.Get***(propName).GetValue(Entity,null);        }    }}

可以使用获取字段值的方式获取主键值。
在和数据库交互的时候,要注意判断主键。外键。
项目被放置到我的git上了,链接[稍后放]

功能差不多实现了。那么问题回来了,reflect到底起到了什么作用。
(题外话,放松一下)有人问过我java开源是什么意思,语言没有所谓的开不开源,因为语言标准明摆的放置在哪里,开源的是标准的实现方法。
在C#中,获取一个对象的实例

Type type = Type.GetType("Entity",true);Entity =  (Entity)System.Activator.CreateInstance(type);

项目传送

原创粉丝点击