2016-08-05 5 views
0

検証プロパティが対応するフィールド名に関連付けられているプロパティを検証する問題に直面しています。 Bindingオブジェクトを検証する際C#プロパティからフィールド名を取得する

int _myIntField; 
public int MyIntField { 
    get { return _myIntField; } 
    set { _myIntField = value; } 
} 

は今、私はプロパティ名MyIntField、ないフィールド名_myIntFieldを返しBindingField、へのアクセス権を持っています。

何とかプロパティの_myIntFieldを取得することはできますか?もしそうなら、どうですか?

+1

さてあなたは、命名規則が固体である場合、あなただけの最初の文字に置き換える... '文字列名=「_」+ Char.ToLowerInvariantを行うことができます(入力[0])+ input.Substring (1); ' – musefan

+1

あなたはロザリンに行くかもしれません。それを行う工場からの方法については、以下を考慮してください: 'int Foo {get {return _bar * _baz> 0? _pete:_barney; }} '。 'Foo'のフィールドは何ですか?ある仮定や別の質問をするコードを書くこともできますが、.NETフレームワークが誰にとっても意味のある、あるいは有用な仮定をする方法はありません。 –

+0

[GetterバッキングフィールドをPropertyInfoから取得するにはどうすればいいですか?](http://stackoverflow.com/questions/38490739/how-to-get-getter-backing-field-from-propertyinfo) – thehennyy

答えて

0

実は、私の場合のために、私は回避策を持っている:私は、パラメータとして関連付けられたフィールド名を取ってカスタム属性を作成し...

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; 
    } 
    } 
関連する問題