[英]How to get the name of a parameter passed to a method?
我目前有一個驗證類,其中包含一個驗證字符串不為空的方法(並記錄信息,但這不是這里的問題)
protected void ValidateStringNotEmpty(string propertyName, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
ValidationErrors.Add($"Property [{propertyName}] must be filled");
}
}
這被稱為使用
ValidateStringNotEmpty(nameof(Name), Name);
是否有一種簡單(和優化)的方法來防止需要傳遞第一個參數nameof(property)
?
我看到了使用 stacktrace 來跟蹤回調的解決方案,但這似乎不是一個很好的解決方案......
編輯:我真正想做的是看看是否存在可以執行此操作的內容(無需傳遞參數名稱)。 我知道務實的解決方案是我已經使用的解決方案,這不是問題。
現在有“CallerArgumentExpression”,它隨 dotnet 6 / C# 10 一起提供,並且完全符合您的要求
protected void ValidateStringNotEmpty(string value, [CallerArgumentExpression("value")] string propertyName = "")
直接在屬性內部驗證並利用[CallerMemberName]
怎么樣?
private string _text;
public string Text
{
get => _text;
set
{
if (IsValid(value))
{
_text = value;
}
else
{
ValidationErrors.Add("'abcd' was expected.");
}
}
}
private bool IsValid<T>(T value, [CallerMemberName] string propertyName = null)
{
switch (propertyName)
{
case nameof(Text):
return value as string == "abcd";
default:
throw new ArgumentOutOfRangeException(nameof(propertyName), propertyName, null);
}
}
public static class ValidationErrors
{
public static void Add(string message, [CallerMemberName] string propertyName = null)
{
throw new NotImplementedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.