注: 本文是給有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 entity
Type 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);