首页 > 解决方案 > 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;
    }       
}

谢谢

标签: c#asp.net-web-api2

解决方案


你可以这样写:

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);

推荐阅读