簡體   English   中英

C#如何使用泛型從類中獲取屬性的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM