繁体   English   中英

C#从属性检索字段名称

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM