【问题标题】:what is an alternative to method overloading to make code a bit less repetitive c#什么是方法重载的替代方法,以减少代码重复c#
【发布时间】:2018-10-09 09:39:52
【问题描述】:

我被方法重载困住了,我想知道玩具如何简化或重做,以便我可以使它成为一个函数

我想知道 我怎样才能简化这个 ->

    print(5);
    print(5.5);
    print("5");  

    static void print (int x)
    {
        Console.WriteLine(x);
    }
    static void print (string x)
    {
        Console.WriteLine(x);
    }
    static void print (double x)
    {
        Console.WriteLine(x);
    }

变成这样 ->

    print(5);
    print(5.5);
    print("5");  

    static void print (int x, string y, double, z)
    {
        Console.WriteLine(x);
    }

【问题讨论】:

    标签: c# string methods int double


    【解决方案1】:

    您确实可以将对象类型作为参数,如前所述。我自己更喜欢使用泛型的更优雅的解决方案:

    static void print<T>(T x) {
        Console.WriteLine(x);
    }
    

    【讨论】:

    • 优雅且完全没用,因为Console.WriteLine 接受object 作为参数,使该特定方法通用化没有任何实用性。它只会让编译器生成不同的方法(它们都会做同样的事情)。
    • Console.WriteLine 可以接受对象类型作为参数,但 asker 的打印函数不接受。
    【解决方案2】:

    让你的参数成为一个通用的object:

    static void print (object o)
    {
        ConSole.WriteLine(o);
    }
    

    这将隐式调用o.ToString

    【讨论】:

      【解决方案3】:

      如果您只使用您认为需要以不同方式处理的不同类型的公共成员,有时您可以避免多次重载。在您的示例中,您根本不需要重载,因为您要处理的所有类型都有一个从object 继承的ToString 方法。因此你可以简单地写:

      void print(object o)
      {
          Console.WriteLine(o.ToString());
      }
      

      假设您想以不同的方式处理数字和字符串,您还可以使用 int 隐式转换为 double 的事实。因此,如果 double 的作用与 double 相同,则无需单独的 int 重载:

      void print(double d)
      {
          Console.WriteLine("I am a number " + d.ToString());
      }
      
      print(1);
      print(1.0); // both works
      

      所以目标始终是找到通用的基类/接口或隐式类型转换,以避免多余的方法重载。

      【讨论】:

        【解决方案4】:

        你只是简单地做了它,但你的函数调用看起来像这样:

        print(5, 5.5, "5");
        

        你的函数应该是这样的:

        static void print (int x, string y, double z)
        {
            Console.WriteLine(x);
            Console.WriteLine(y);
            Console.WriteLine(z);
        }
        

        【讨论】:

        • 他并不是我想的那样。他展示了使用不同参数类型调用 print 函数的树示例。
        • 哦,哇。我真的错过了。我会使用泛型,但对象也可以。谢谢。
        猜你喜欢
        • 1970-01-01
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2015-02-13
        相关资源
        最近更新 更多