Может ли быть создан метод для повторения кода? - PullRequest
0 голосов
/ 01 ноября 2019

Я ищу способ сделать метод для повторного кода ниже (последний блок кода внизу). В настоящее время я передаю строку [] и проверяю, является ли она каким-либо из объектов eventHubResource.Blah. Вот мой класс EventHubResource:

public class EventHubResource : IResource
{
    public string[] ListenManageRuleNames { get; set; }
    public string[] SendManageRuleNames { get; set; }
    public string[] SendListenRuleNames { get; set; }
    public string[] ManageRuleNames { get; set; }
    public string[] ListenRuleNames { get; set; }
    public string[] SendRuleNames { get; set; }
    public string[] ConsumerGroups { get; set; }
    public int MessageRetention { get; set; }
    public int PartitionCount { get; set; }
    public string Id { get; set; }
    public string Name { get; set; }
    public ResourceGroup ResourceGroup { get; set; }
    public Dictionary<string, string> Tags { get; set; }
}

Но, очевидно, этого не может быть, потому что значение после case должно быть константой. Я думал сделать что-то вроде этого (это показывает только один из повторяющихся блоков в операторе switch):

public async void UpdateEventHub(string[] array, EventHubResource eventHubResource)
{
    if (!Utils.IsNullOrEmpty(array))
    {
        switch (array)
        {
            case eventHubResource.SendRuleNames:
                foreach (var sendRuleNames in eventHubResource.SendRuleNames)
                    {
                        await eventHub.Update()
                            .WithNewSendRule(sendRuleNames)
                            .ApplyAsync();
                    };
            # all of the other cases
            default:
                break;
        }
    }
}

Вот повторение кода, который у меня есть, где eventHubResource.Blah это тип string []:

if (!Utils.IsNullOrEmpty(eventHubResource.ConsumerGroups))
{
    foreach (var consumerGroup in eventHubResource.ConsumerGroups)
    {
        await eventHub.Update()
            .WithNewConsumerGroup(consumerGroup)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.SendRuleNames))
{
    foreach (var sendRuleNames in eventHubResource.SendRuleNames)
    {
        await eventHub.Update()
            .WithNewSendRule(sendRuleNames)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.ListenRuleNames))
{
    foreach (var listenRuleNames in eventHubResource.ListenRuleNames)
    {
        await eventHub.Update()
            .WithNewListenRule(listenRuleNames)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.ManageRuleNames))
{
    foreach (var manageRuleNames in eventHubResource.ManageRuleNames)
    {
        await eventHub.Update()
            .WithNewManageRule(manageRuleNames)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.SendListenRuleNames))
{
    foreach (var sendListenRuleNames in eventHubResource.SendListenRuleNames)
    {
        await eventHub.Update()
            .WithNewSendRule(sendListenRuleNames)
            .WithNewListenRule(sendListenRuleNames)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.SendManageRuleNames))
{
    foreach (var sendManageRuleNames in eventHubResource.SendManageRuleNames)
    {                       
        await eventHub.Update()
            .WithNewSendRule(sendManageRuleNames)
            .WithNewManageRule(sendManageRuleNames)
            .ApplyAsync();
    }
}

if (!Utils.IsNullOrEmpty(eventHubResource.ListenManageRuleNames))
{
    foreach (var listenManageRuleNames in eventHubResource.ListenManageRuleNames)
    {
        await eventHub.Update()
            .WithNewListenRule(listenManageRuleNames)
            .WithNewManageRule(listenManageRuleNames)
            .ApplyAsync();
    }
}

Любая помощь очень важна, и дайте мне знать, если вам нужна дополнительная информация.

1 Ответ

0 голосов
/ 01 ноября 2019
public void Run(string[] list, Func<IQueryable, IQuerayble> action)
{
    if (!Utils.IsNullOrEmpty(list))
    {
        foreach (var listenManageRuleNames in list)
        {
             var query = eventHub.Update();
             query = action(query); 
             await query.ApplyAsync();
        }
    }
}

И вы вызываете это с помощью

Run(eventHubResource.ConsumerGroups, WithNewConsumerGroup);
Run(eventHubResource.SendRuleNames, WithNewSendRule);
Run(eventHubResource.ListenRuleNames, WithNewListenRule);

Точный синтаксис зависит от типов, которые генерирует ваш eventHub.Update ().

...