退出 while 循环 [关闭] 的正确方法是什么

问题描述 投票:0回答:2

我收到提示,要求用户输入用户名并选择要添加到 Active Directory (AD) 中的组。我的想法是,当用户输入用户名,但随后决定他们希望另一个用户返回并提示用户输入不同的用户名进行编辑时。我怎样才能实现这个目标?

目前,这是我的设置

 public void AddUserToGroup(PrincipalContext context)
 {
     bool isExit = false;
     List<string> actionLog = new List<string>();                                                                                                               // Email log list

     do
     {
         Console.Write("Enter the username(Type 'exit' to go back to menu): ");
         string username = Console.ReadLine().Trim();
         if (username.ToLower().Trim() == "exit")
         {
            // isExit = true;
             Console.WriteLine($"\nReturing to menu...");
             break;
         }
         Console.Write("Enter the group name (Type 'exit' to go back to menu): ");
         string groupName = Console.ReadLine().Trim();
         if (groupName.ToLower().Trim() == "exit")
         {
            // isExit = true;
             Console.WriteLine($"\nReturing to menu...");
             break;
         }
         else
         {
             try
             {
                 UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);                                              // Check for user in AD

                 if (user != null)
                 {

                     GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);                                                                   // Check for group in AD

                     if (group != null)
                     {
                         if (!group.Members.Contains(user))                                                                                                      // If the user is not in the group add him
                         {
                             group.Members.Add(user);                                                                                                            // Add the user to the group
                             group.Save();                                                                                                                       // Apply changes
                             group.Dispose();
                             Console.ForegroundColor = ConsoleColor.Green;
                             Console.WriteLine($"User '{username}' added to group '{groupName}' successfully.");
                             Console.ForegroundColor = ConsoleColor.Gray;

                             string logEntry = ($"\"{user.DisplayName}\" has been Added to \"{groupName}\" group in Active Directory\n");
                             actionLog.Add(logEntry);
                             auditLogManager.Log(logEntry);

                         }// end of inner-2 if-statement
                         else
                         {
                             Console.ForegroundColor = ConsoleColor.DarkYellow;
                             Console.WriteLine($"User '{username}' is already a member of group '{groupName}'.");
                             Console.ForegroundColor = ConsoleColor.Gray;
                         }// end of inner-2 else-statement
                     }// end of inner if-statement
                     else
                     {
                         Console.ForegroundColor = ConsoleColor.DarkRed;
                         Console.WriteLine($"Group '{groupName}' not found in Active Directory.");
                         Console.ForegroundColor = ConsoleColor.Gray;
                     }// end of outter else-statement
                 }// end of outter if-statement 
                 else
                 {
                     Console.ForegroundColor = ConsoleColor.DarkRed;
                     Console.WriteLine($"User '{username}' not found in Active Directory.");
                     Console.ForegroundColor = ConsoleColor.Gray;
                 }
             }// end of try
             catch (Exception ex)
             {
                 Console.ForegroundColor = ConsoleColor.Red;
                 Console.WriteLine($"Error adding user to group: {ex.Message}");
                 Console.ForegroundColor = ConsoleColor.Gray;
             }// end of catch
         }
     } while (!isExit);
     if(actionLog.Count > 0 )
     {
         string emailBody = string.Join("\n", actionLog);
         emailNotifcation.SendEmailNotification("ADUtil Action: Administrative Action in Active Directory", emailBody);
     }// end of if statement
 }// end of AddUserToGroup
c# while-loop do-while
2个回答
1
投票

不幸的是,C# 不支持非本地返回(所以我很羡慕 Kotlin 用户),但是您可以将逻辑重构为单个可重用循环,您可以将其移至其自己的函数中 - 只需将

null
保留为退出/退出情况的特殊值:

如果您使用的是 C# 的半新版本,您可以将其重构为

static
本地函数,这很方便 - 但类级
static
方法也很好。

public static void Main()
{
    static String? Prompt( String msg, Func<String,Boolean> isValid )
    {
        while( true )
        {
            Console.WriteLine( msg );
            String input = Console.ReadLine()?.Trim() ?? String.Empty;
            if( "q".Equals( input, StringComparison.OrdinalIgnoreCase ) ) return null;
            else if( isValid( input ) ) return input;
        }
    }

    // 

    String? userName = Prompt( "Enter the username - or enter 'q' to quit", str => !String.IsNullOrWhitespace( str ) );
    if( userName is null ) return;

    String? groupName = Prompt( "Enter the group-name - or enter 'q' to quit", str => !String.IsNullOrWhitespace( str ) );
    if( groupName is null ) return;

    //

    DoStuff( userName, groupName );
}

-1
投票

您可以尝试使用的另一种方法是使用本质上作为休息的标签;命令,但用于 do-while 循环。

bool isExit = false;
    do
    {
        Console.Write("Enter the username(Type 'exit' to go back to menu): ");
        string username = Console.ReadLine();
        if (username.ToLower() == "exit") {
            goto exitLoop;
        }
        Console.Write("Enter the group name (Type 'exit' to go back to menu): ");
        string groupName = Console.ReadLine();

        if (groupName.ToLower() == "exit") {
            goto exitLoop;
        }
    } while (!IsExit);
exitLoop:
isExist = true;
//continue rest of your code.
© www.soinside.com 2019 - 2024. All rights reserved.