![](/img/trans.png)
[英]C# Generics: How to use nameof to get the name of a base class property
[英]C# how to get value of a property from a class using generics
我正在研究 asp.net core webapi 並使用 appsettings.json 來存儲一些設置。 我有一個類可以使用 IOptions<> 從 appsettings 獲取屬性值。
想知道是否有一種簡單的方法可以使用泛型來獲取屬性值,而不是像我在下面所做的那樣創建單獨的方法名稱:
public class NotificationOptionsProvider
{
private readonly IOptions<NotificationOptions> _notificationSettings;
public NotificationOptionsProvider(IOptions<NotificationOptions> notificationSettings)
{
_notificationSettings = notificationSettings;
InviteNotificationContent = new InviteNotificationContent();
}
public string GetRecipientUserRole()
{
if (string.IsNullOrWhiteSpace(_notificationSettings.Value.RecipientUserRole))
{
throw new Exception("RecipientUserRole is not configured");
}
return _notificationSettings.Value.RecipientUserRole;
}
public string GetInvitationReminderTemplateCode()
{
if (string.IsNullOrWhiteSpace(_notificationSettings.Value.AssignReminderTemplateCode))
{
throw new Exception("InvitationReminderTemplateCode is not configured");
}
return _notificationSettings.Value.AssignReminderTemplateCode;
}
public string GetSessionBookedTemplateCode()
{
if (string.IsNullOrWhiteSpace(_notificationSettings.Value.SessionBookedTemplateCode))
{
throw new Exception("SessionBookedTemplateCode is not configured");
}
return _notificationSettings.Value.SessionBookedTemplateCode;
}
}
謝謝
你可以這樣寫:
public string GetSetting(Func<NotificationOptions, string> selector)
{
string value = selector(_notificationSettings.Value);
if (string.IsNullOrWhiteSpace(value))
{
throw new Exception("Not configured");
}
return value;
}
並稱之為:
GetSetting(x => x.AssignReminderTemplateCode);
只是詳細闡述了 canton7 的優秀答案; 您可以像這樣保留異常文本:
public string GetSetting(Expression<Func<NotificationOptions, string>> selector)
{
Func<NotificationOptions, string> func = selector.Compile();
string value = selector(_notificationSettings.Value);
if (string.IsNullOrWhiteSpace(value))
{
var expression = (MemberExpression)selector.Body;
throw new Exception($"{expression.Member.Name} is not configured");
}
return value;
}
盡管請注意對.Compile()
的調用會影響性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.