2017-05-31 22 views
1
各地成員名稱中使用nameof

我在這工作正常,並提出驗證消息上我認爲我的視圖模型下面的代碼:中的ValidationResult

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
{ 
    yield return new ValidationResult("Required", new[] { "Insured.FirstName" }); 
} 

不過,我想引用成員名稱,而不使用字符串文字,所以我試圖將其更改爲以下內容:

yield return new ValidationResult("Required", new[] { nameof(Insured.FirstName) }); 

這不起作用。驗證消息不會出現在我的視圖中。這是不支持,或者我不正確地做這個?

+2

很肯定'nameof(Insured.FirstName)'僅返回「FirstName」。 – Quantic

+0

@Quantic你知道是否有可能使用nameof返回完整的「Insured.FirstName」? –

+2

嗯,我只是在搜索周圍,並找到人寫作爲您構建名稱的方法,如[this](https://stackoverflow.com/a/39296258/5095502)或[this one](https: //stackoverflow.com/a/36009266/5095502)。在你的情況下,你可以通過'nameof(被保險人)+「來得到。」 + nameof(FirstName)'。 – Quantic

回答

0

多虧了上述評論最後我把這個在公用事業類:

public static class Utilities 
{ 
    public static string GetPathOfProperty<T>(Expression<Func<T>> property) 
    { 
     string resultingString = string.Empty; 
     var p = property.Body as MemberExpression; 
     while (p != null) 
     { 
      resultingString = p.Member.Name + (resultingString != string.Empty ? "." : "") + resultingString; 
      p = p.Expression as MemberExpression; 
     } 
     return resultingString; 
    } 
} 

,然後我可以做到以下幾點:

yield return new ValidationResult("Required", new[] { Utilities.GetPathOfProperty(() => Insured.FirstName) }); 
相關問題