我在C#(.NET 2.0)中有一个代码,在其中我用输入Enum调用了一个方法,但是我无法使其正常工作。
我在方法isAnOptionalBooleanValue中有一个编译错误:
public static bool isAnOptionalBooleanValue(Status status, String parameterName,
Object parameter) {
return isAnOptionalValidValue(status, parameterName, parameter,
UtilConstants.BooleanValues);
}
public static bool isAnOptionalValidValue(Status status, String parameterName,
Object parameter, Enum setOfValues)
{
....
}
Run Code Online (Sandbox Code Playgroud)
在其他班级:
public class UtilConstants
{
public enum BooleanValues
{
TRUE, FALSE
}
}
Run Code Online (Sandbox Code Playgroud)
之所以存在此类,是因为布尔值是来自其他系统的输入String,因此我将其作为Object传递并将其从Enum类转换为Boolean。
它返回的错误如下:“ UtilConstants.BooleanValues'是'type',在给定的上下文中无效”,返回isAnOptionalValidValue(...)行中的错误。
但是我看不出如何解决它。通过以下方式进行更改:
返回isAnOptionalValidValue(状态,parameterName,参数,typeof(UtilConstants.BooleanValues));
也不起作用。
有任何想法吗?提前谢谢你的帮助!
UtilConstants.BooleanValues您需要使用实际值而不是(实际上是类型而不是值)。像这样:
UtilConstants.BooleanValues.TRUE | UtilConstants.BooleanValues.FALSE
Run Code Online (Sandbox Code Playgroud)
或者,如果您实际上要检查输入字符串是否与枚举类型的常量匹配,则应更改签名:
public static bool isAnOptionalValidValue(Status status, String parameterName,
Object parameter, Type enumType)
Run Code Online (Sandbox Code Playgroud)
这样,您建议的方法调用typeof就可以使用。
然后,您可以通过调用获取枚举的实际String值Enum.GetValues(enumType)
小智 5
您可能宁愿使用
bool myBool;
Boolean.TryParse("the string you get from the other system", out myBool);
Run Code Online (Sandbox Code Playgroud)
而不是重新定义布尔。
您也可以将其作为可空布尔值“可选”(因此,如果没有true值,则为false,它为null):
bool? myBool = null;
bool tmp;
if (Boolean.TryParse("the string you get from the other system", out tmp))
myBool = tmp;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18552 次 |
| 最近记录: |