繁体   English   中英

方法重载null参数

[英]Method Overloading null parameter

在我的代码中,我有一个必须采用4个参数的方法。 但是在代码的某处,我有时用2个参数,有时用4个参数来调用此方法。 因此,当我使用2个参数调用时,最后2个参数应自动​​为空。

例如:

public static void x(String one,String two,String three=null,String four=null){

//do something hear

}

x("one","two");
x("one","two","three","four");

当我调用x(“ one”,“ two”)=>时,我希望三个和四个参数automatticaly初始化为null。

我怎样才能做到这一点 ? 感谢您的帮助。

class A{

   public void do(String a, String b, String c, String d){
        //do something
   }

   //Overload do method
   public void do(String a, String b){
        do(a,b,null,null);
   }
}

最好的选择是让您的方法仅包含4个参数,仅当您只需要传递2个参数时,将其他2个参数传递为null。

例如2个参数传递:

    x(a,b,null,null);

并通过4个参数:

    x(a,b,c,d);

这也可以正常工作,并且可以使用字符串数组作为参数或多个逗号分隔的字符串来调用。 这样,您不必超载。

public void myMethod(String ...strings)  {
    for (String string : strings) {
        //do something with the string
    }
}

您可以使用数组来调用它:

myMethod(new String[]{"test1", "test2"})

或几个字符串:

myMethod("test1", "test2");
myMethod("test1", "test2", "test3", "test4");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM