[英]C# Retrieve field name from property
I am facing the issue of validating a property whose validation properties are associated with the corresponding field name. 我面临的问题是验证其验证属性与相应字段名称相关联的属性。
int _myIntField;
public int MyIntField {
get { return _myIntField; }
set { _myIntField = value; }
}
Now, when validating a Binding
Object, I have access to the BindingField
, which returns the property name MyIntField
, not the field name _myIntField
. 现在,当验证Binding
对象时,我可以访问BindingField
,它返回属性名称MyIntField
,而不是字段名称_myIntField
。
Is it possible to somehow retrieve _myIntField
for the property? 是否可以以某种方式检索_myIntField
的属性? If so, how? 如果是这样,怎么办?
Actually, for my case, I have a work-around: I created a custom attribute taking the associated field name as a parameter... 实际上,对于我而言,我有一个解决方法:我创建了一个自定义属性,将关联的字段名称作为参数...
int _myIntField;
[MyAttribue("_myIntField")]
public int MyIntField {
get { return _myIntField; }
set { _myIntField = value; }
}
For the sake of completeness, here is the attribute's declaration: 为了完整起见,这是属性的声明:
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.