C# 如何避免多个开关(委托?)

发布于 2025-01-08 13:00:46 字数 1398 浏览 5 评论 0原文

我在代码中使用多个开关来反映列表框中的物种选择。其中之一看起来像:

    private int getOrganelleLength() {
        int species = listBox1.SelectedIndex;

        switch (species) {
            case 0:
                //Console.WriteLine("arabidopsis");
                return 154478;

            case 1:
                //Console.WriteLine("oryza");
                return 134525;

            case 2:
                //Console.WriteLine("glycine");
                return 152218;

            default:
                Console.WriteLine("Error");
                throw new Exception("wrong speices choice");
        }
    }

第二个看起来像:

    private int getLengthOfChromosome(int number) {

        int species = listBox1.SelectedIndex;

        switch (species) {
            case 0:
                //Console.WriteLine("arabidopsis");
                return arabidopsis_chromosomes[number - 1];

            case 1:
                //Console.WriteLine("oryza");
                return oryza_chromosomes[number - 1];

            case 2:
                //Console.WriteLine("glycine");
                return glycine_chromosomes[number - 1];

            default:
                Console.WriteLine("Error");
                throw new Exception("wrong speices choice");
        }

我不知何故觉得这不是最清晰的解决方案,这种多次使用开关。然而,这两个函数返回完全不同的值(当然,基于物种选择)。如果有办法的话,我很想学习如何改进我的代码。多谢。

I am using multiple switches in my code to reflect species choice in listbox. One of them looks like:

    private int getOrganelleLength() {
        int species = listBox1.SelectedIndex;

        switch (species) {
            case 0:
                //Console.WriteLine("arabidopsis");
                return 154478;

            case 1:
                //Console.WriteLine("oryza");
                return 134525;

            case 2:
                //Console.WriteLine("glycine");
                return 152218;

            default:
                Console.WriteLine("Error");
                throw new Exception("wrong speices choice");
        }
    }

second looks like:

    private int getLengthOfChromosome(int number) {

        int species = listBox1.SelectedIndex;

        switch (species) {
            case 0:
                //Console.WriteLine("arabidopsis");
                return arabidopsis_chromosomes[number - 1];

            case 1:
                //Console.WriteLine("oryza");
                return oryza_chromosomes[number - 1];

            case 2:
                //Console.WriteLine("glycine");
                return glycine_chromosomes[number - 1];

            default:
                Console.WriteLine("Error");
                throw new Exception("wrong speices choice");
        }

I somehow feel that this is not the clearest solution, this multiple use of switch. However, both functions return completely different values (based on species choice, of course). I would love to learn how to improve my code, if there is a way to. Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怪我鬧 2025-01-15 13:00:47

看看重构方法。这听起来像用多态性替换条件

因此请为数据对象使用类。

Take a look on refacotring methods. This sounds like Replace Conditional with Polymorphism

So use classes for your data objects.

假装爱人 2025-01-15 13:00:47

您可以这样写:

private int getOrganelleLength() {
    var dict = new Dictionary<int, int>() { {0, 154478}, {1, 134525}, {2, 152218} };
    return dict[listBox1.SelectedIndex];
}

private int getLengthOfChromosome(int number) {
    var dict = new Dictionary<int, Func<int>>() {
           {0, () => arabidopsis_chromosomes[number - 1]},
           {1, () => oryza_chromosomes[number - 1]}
           {2, () => glycine_chromosomes[number - 1]}}; 
    return dict[listBox1.SelectedIndex]();
 }

在最后一种情况下,您实际上不需要 Func,因为您只需添加到字典值 arabidopsis_chromosomes 即可,为示例编写了更多内容。

无论如何,只有当你有非常非常简单的开关时,这才有效。 如果您需要编写一些更困难的内容,请不要使用它。在这种情况下,您应该重构代码并使用多态性和工厂。

You could write:

private int getOrganelleLength() {
    var dict = new Dictionary<int, int>() { {0, 154478}, {1, 134525}, {2, 152218} };
    return dict[listBox1.SelectedIndex];
}

private int getLengthOfChromosome(int number) {
    var dict = new Dictionary<int, Func<int>>() {
           {0, () => arabidopsis_chromosomes[number - 1]},
           {1, () => oryza_chromosomes[number - 1]}
           {2, () => glycine_chromosomes[number - 1]}}; 
    return dict[listBox1.SelectedIndex]();
 }

In the last case you don't need actually Func, as you can just add to dictionary values arabidopsis_chromosomes, wrote that more for an example.

Anyway that will work only if you have very very simple switch. If you need some more difficult stuff to write, do not use that. For that case you should refactor your code and use polymorphism and factories.

愿与i 2025-01-15 13:00:47

首先,您应该在 default 情况下抛出 NotImplementedException,而不是 Exception

然后,您应该看看 Func委托

您可以让您的代码看起来像这样,

private int GetInformationAboutSpecies(ListBox listBox, ISwitchCaseResolver helper)
{
    return helper.GetInformation(listBox.SelectedIndex);
}

然后您可以为每个物种实现一个具体的 ISwitchCaseResolver 接口类。您还可以考虑使用工厂模式来调用您的界面。

First, you should throw a NotImplementedException in your default case and not an Exception.

Then, you should take a look at Func<T, TResult> delegate.

You could have your code looking something like

private int GetInformationAboutSpecies(ListBox listBox, ISwitchCaseResolver helper)
{
    return helper.GetInformation(listBox.SelectedIndex);
}

You can then implement a concrete class of ISwitchCaseResolver interface for each of your species. You may also consider using a Factory pattern to call the correct implemtantion of your interface.

归属感 2025-01-15 13:00:46

我假设 arabidopsis_chromosomes 等是数组或列表。

只需将它们添加到数组或列表中即可。

例如(极其简化):

object[][] foo = {{ 1,2,3}, {4,5,6}};

object Get(int x, int y)
{
  return foo[x][y];
}

I assume arabidopsis_chromosomes et al, are arrays or lists.

Just add them to an array or list.

Eg (extremely simplified):

object[][] foo = {{ 1,2,3}, {4,5,6}};

object Get(int x, int y)
{
  return foo[x][y];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文