How to use a switch statement with Guid?

后端 未结 2 1708
囚心锁ツ
囚心锁ツ 2021-01-17 13:51

In the following C# code, cboRole returns a Guid.

I\'m then trying to use it in a switch statement to do some actions.

cboRole can return only 4 different G

相关标签:
2条回答
  • 2021-01-17 14:00

    with c#7 you can now use switch with Pattern Matching for this purpose.

    switch (cboRole)
    {
        case var r when (r == new Guid("532E8EED-9E72-42E0-871E-36470C1AE327")):
            param1 = "4E08BA7C-E81F-40AE-92F0-DF33A98DD0BB";
            MessageBox.Show("It's working");
            break;
        case var r when (r == new Guid("FA7637E9-A9E4-4D57-A59B-80615424D27F")):
            param1 = "E540C382-F22C-4FE2-9068-1E10AA8DD076";
            break;
        case var r when (r == new Guid("2734CCD9-93E6-4A86-8B83-5EA9E62FA921")):
            param1 = "8A54F8D5-5B74-4B3F-A29A-D423AA8DD02E";
            break;
        default:
            MessageBox.Show("Not Working");
            break;
    }
    

    This also works if you have defined static readonly new Guid"..") variables.

    0 讨论(0)
  • 2021-01-17 14:22

    Your switch statements are in upper-case while your ToStringEx() returns the Guid in lower-case.

    You can use

    switch (cboRole.EditValue.ToStringEx().ToUpper())
    

    or modify your case statements.

    0 讨论(0)
提交回复
热议问题