C 通過特性驗證實體屬性值

2022-03-31 08:14:39 字數 1285 閱讀 3917

一,什麼是特性

特性也是一種物件,特殊之處在於其編譯時就存在了,也就是在程式執行之前就存在了。

二,如何定義乙個特性

[attributeusage(attributetargets.property |attributetargets.field)]

public

sealed

class

requiredattribute:attribute

}

三,特性驗證實體屬性正確性

///

///資料特性驗證的基類

/// public

abstract

class

abstractvalidateattribute : attribute

資料特性驗證的基類

[attributeusage(attributetargets.property |attributetargets.field)]

public

sealed

class

nullemptyattribute : abstractvalidateattribute

}

1

public

static

class

attributeextend

2的值不可為

", prop.name, prop.getvalue(tmodel, null) == null ? "

null

" : prop.getvalue(tmodel, null

).tostring()));17}

18}19}

20}21//

return false;22}

2324

25 }

1

public

class

student24

[nullempty]

5public

string name

6 }

1

try2

6catch

(exception ex)710

11 console.readkey();

顯示結果:

原始碼github:       

通過特性動態獲取屬性及值

using system.collections.generic using system.data.sqlclient using system.data using system namespace npetshop.domain 獲取或設定name欄位的值 system.string 資料庫型...

通過特性動態獲取屬性及值

using system.collections.generic using system.data.sqlclient using system.data using system namespace npetshop.domain 獲取或設定name欄位的值 system.string 資料庫型...

通過反射獲取實體物件的屬性及對應的屬性值

需求 需要獲取實體物件的屬性及屬性值作為key value形式的namevaluepair引數,用於post請求的引數,為了避免一大段的get 考慮使用反射方式進行設定,示例 如下 public class person public void setname string name public ...