C# 如何使用泛型从 class 中获取 属性 的值

C# how to get value of a property from a class using generics

我正在研究 asp.net 核心 webapi 并使用 appsettings.json 来存储一些设置。我有一个 class 可以使用 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() 会影响性能。