C 反射,特性結合使用

2021-07-11 09:38:34 字數 1217 閱讀 7068

using system;

using system.reflection;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading.tasks;

}//model

[dbtablename("connectionstring")]

public class student

[dbfield]

public string name

[dbfield]

public int age

}//control

public class studentbllwhere t:class,new()

dbtablenameattribute _dbtablenameattribute = model.gettype().getcustomattribute();

console.writeline("the database connection string is "+_dbtablenameattribute._dbconnection);

return model;}}

//attribute

[attributeusage(attributetargets.class, allowmultiple=false, inherited=false)]

public class dbtablenameattribute : attribute

public dbtablenameattribute(string dbconnection)

}[attributeusage(attributetargets.property,allowmultiple=false,inherited=false)]

public class dbfield:attribute

public dbfield(bool iskeyid)

public bool getiskeyid }}

}

上面這些**能幹嘛呢?

例如上面的:studentbll,你可以將它封裝成basebll,在裡面實現各種資料庫的增、刪、查、改操作,外面的model模型只要用dbfield特性標記,那就可以將model與對應的資料庫的資料表聯絡起來,方便將model持久化到資料庫裡面。

C 使用反射訪問特性

ms註解 如果沒有檢索自定義特性的資訊和對其進行操作的方法,則定義自定義特性並將其放置在源 中就沒有意義。使用反射,可檢索用自定義特性定義的資訊。主要方法是getcustomattributes,它返回物件陣列,這些物件在執行時等效於源 特性。此方法具有多個過載版本 例項 multiuse attr...

特性的使用,反射

1.自定義特性允許吧自定義元資料與元素關聯起來。這些元資料是在編譯過程中建立的,並嵌入到程式集中。反射是乙個普通術語,他描述了了在執行過程中檢查和處理程式元素的功能。反射可以完成以下任務 列舉型別的成員 例項化新物件 執行物件的成員 查詢型別的資訊 查詢程式集的資訊 檢查應用於某種型別的自定義特性 ...

反射簡介 C 特性和反射

net編譯器的任務之一就是為所有定義和引用的型別生成元資料描述。除了程式集中標準的元資料外,net平台還支援特定 attribute 把更多的元資料嵌入到程式集中。net特性擴充套件了抽象的system.attribute基類,net中有很多預定義的特性,例如 dllimport obsolete ...