![](/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.