方法,可选参数和/或接受多种数据类型 [英] Methods, Optional Parameters and/or Accepting multiple Data Types

查看:121
本文介绍了方法,可选参数和/或接受多种数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览网络一段时间后,找不到我的问题的答案.

After browsing the web for a while looking for an answer to my question I can't find any posts which seem to offer an effective solution to my issue.

当前,我将为每个不同的数据类型输入重载一个方法.

Currently I would overload a method for each different data type input.

例如:

public void ex1(String in){
public void ex1(int in){

我想有一种方法可以将其压缩为一行

I would imagine there would be a way to condense this into one line

public void ex1(opt(String in), opt(int in)){

public void ex1((String/int) in){

但是,据我所知,没有人提出使用这两种形式的合理方法.

However, as far as I've seen, nobody has presented a reasonable method to use either of these forms.

重载确实可以工作,但看起来却不尽如人意,因此,任何变通方法或想法都将不胜感激.

Overloading does work, but doesn't look as clean as I might like it, so any workarounds or ideas would be appreciated.

推荐答案

有一种方法,但是您只能提供one可选参数. 那就是在参数类型前面使用....

There is a way, but you acn only provide one optional parameter. That way is to use ... in front of parameter type.

例如:

public void ex1(int someint, String... in)){

在这种情况下,String in是一个可选参数,您可以提供或不提供.但是int someint是必须提供的参数.

In this case String in is an optional parameter which you can provide or not. But int someint is a must provide parameter.

所以String... in基本上是String[] in.由于array可以为null....除此以外(至少我)不知道实现此目的的任何其他方法.

So String... in is basically a String[] in. Since array can be null.... Other than this (atleast I) dont know of any other way to achieve this.

这意味着您也无法执行必须输入其中一个参数而可以忽略其他参数之类的操作.您可以仅忽略一个参数,而其他参数则必须传递.

This means you also cant do something like one of the parameters has to be entered and other can be ignored. You can ignore just one parameter and other has to be passed.

这也适用于每个方法一个参数.换句话说,仅一个参数可以设为可选.否则,您必须使用方法重载.

Also this works with just one parameter per method. In other words, just one parameter can be made optional. Else you must use method overloading.

但是(如评论中所述),这不是一种有效的方法.与方法重载的有效方法相比,既然您必须为每个变量的可能性编写逻辑,并且代码将是一团糟.

However (as said in comments), this is not an effective way. Since you will have to write logic for each varaible's possibility and the code would be a great mess, compared to the sweet and effective way by method overloading.

varargs (或此可选参数)必须作为方法中的最后一个参数出现.感谢@Makoto指出这一点.

varargs (or this optional parameter) must appear as the last parameter in method. Thanks @Makoto for pointing this out.

这篇关于方法,可选参数和/或接受多种数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆