c# - C#如何使用泛型从类中获取属性的值
问题描述
我正在研究 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);
推荐阅读
- ruby-on-rails - 如何在创建方面运算符的数组上查找 id
- node.js - ExpiresIn 与 maxAge
- conditional-formatting - 使用 Epplus 读取电子表格并确定所有单元格的样式,包括条件格式
- batch-file - 使用批处理打开和关闭excel而不丢失数据
- php - 试图弄清楚如何使用 Curl_multi 进行异步 GET 请求。代码没有返回预期的东西,但也没有给出错误
- c# - HTML 敏捷包如何找到文本的某些部分
- jquery - 更改选择框字体大小影响选项项长度
- javascript - 数组中的对象并没有真正按预期工作
- ios - 用整个单词而不是一个字符来分割字符串
- python - 如何使用从 CSV 文件中提取的 OrderedDict 为 DB 构建表