• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

方法,可选参数和/或接受多种数据类型

用户头像
it1352
帮助1

问题说明

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

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.

正确答案

#1

有一种方法,但是您只能提供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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfiagk
系列文章
更多 icon
同类精品
更多 icon
继续加载