[英]C# Retrieve field name from property
我面臨的問題是驗證其驗證屬性與相應字段名稱相關聯的屬性。
int _myIntField;
public int MyIntField {
get { return _myIntField; }
set { _myIntField = value; }
}
現在,當驗證Binding
對象時,我可以訪問BindingField
,它返回屬性名稱MyIntField
,而不是字段名稱_myIntField
。
是否可以以某種方式檢索_myIntField
的屬性? 如果是這樣,怎么辦?
實際上,對於我而言,我有一個解決方法:我創建了一個自定義屬性,將關聯的字段名稱作為參數...
int _myIntField;
[MyAttribue("_myIntField")]
public int MyIntField {
get { return _myIntField; }
set { _myIntField = value; }
}
為了完整起見,這是屬性的聲明:
public class MyAttribue : ValidationAttribute {
protected readonly string _fieldName;
public MyAttribue(string fldName) {
_fieldName = fldName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (validationContext == null) {
return ValidationResult.Success;
}
ErrorMessage = string.Empty;
if (validationContext.ObjectInstance != null) {
// do whathever validation is required using _fieldName...
}
//
if (!string.IsNullOrWhiteSpace(ErrorMessage)) {
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.