Java:方法中的枚举参数 [英] Java: Enum parameter in method

查看:132
本文介绍了Java:方法中的枚举参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  private static String drawCellValue(
int maxCellLength,String cellValue,String对齐){}

并且您可以注意到,我有一个名为align的参数。在这个方法里面我会有一些if条件是否值为'左'或'右'..将参数设置为String,显然我可以传递任何字符串值..我想知道是否可能有一个枚举值作为方法参数,如果是,那么如何?



如果有人想到这个;我考虑使用一个布尔值,但我并不喜欢它。首先,如何将true / false与左/右相关联? (好的,我可以使用评论,但我仍然觉得很脏),其次,我可能会决定添加一个新的值,如对齐,所以如果我有超过2个可能的值,布尔类型绝对不可能使用。



任何想法?

解决方案

应该这样做: p>

  private enum Alignment {LEFT,RIGHT}; 
String drawCellValue(int maxCellLength,String cellValue,Alignment align){
if(align == Alignment.LEFT)
{
//处理...
}
}


I have a method lets say:

private static String drawCellValue(
    int maxCellLength, String cellValue, String align) { }

and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?

Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.

Any ideas?

解决方案

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

这篇关于Java:方法中的枚举参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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