5

我在 C# (.NET 2.0) 中有一个代码,我在其中调用一个带有输入枚举的方法,但我无法让它工作。

我在方法 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)
{
     ....
}

在其他班级:

public class UtilConstants
{
    public enum BooleanValues
    {
        TRUE, FALSE
    }
}

这个类的存在是因为布尔值作为来自其他系统的输入字符串,所以我将它作为一个对象传递并从我的 Enum 类将它转换为布尔值。

它返回的错误如下:“UtilConstants.BooleanValues' 是一个'类型',在给定的上下文中无效”返回 isAnOptionalValidValue(...) 行中的错误。

但我不知道如何解决它。通过以下方式更改它:

return isAnOptionalValidValue(status, parameterName, parameter, typeof(UtilConstants.BooleanValues));

也不起作用。

有任何想法吗?提前谢谢你的帮助!

4

4 回答 4

7

而不是UtilConstants.BooleanValues(它确实是一种类型而不是一个值),您需要使用实际值。像这样:

UtilConstants.BooleanValues.TRUE | UtilConstants.BooleanValues.FALSE

或者,如果您确实想检查输入字符串是否与枚举类型的常量匹配,则应更改签名:

public static bool isAnOptionalValidValue(Status status, String parameterName,
                                          Object parameter, Type enumType)

这样,您建议的方法调用 usingtypeof将起作用。
然后,您可以通过调用获取枚举的实际字符串值Enum.GetValues(enumType)

于 2013-04-02T13:14:44.920 回答
6

你可能宁愿使用

bool myBool;    
Boolean.TryParse("the string you get from the other system", out myBool);

而不是重新定义 bool。

您也可以将其“可选”为可空 bool(因此,如果没有 true 值,则 false 为空):

bool? myBool = null;
bool tmp;
if (Boolean.TryParse("the string you get from the other system", out tmp))
    myBool = tmp;       
于 2013-04-02T13:16:29.560 回答
2

Enum setOfValues在参数列表中意味着您传递特定的值,例如BooleanValues.TRUE- 不是类型本身。传递类型使用Type setOfValues.

从字符串使用解析特定枚举值

BooleanValues enumValue = (BooleanValues)Enum.Parse(typeof(UtilConstants.BooleanValues), stringValue);
于 2013-04-02T13:15:49.063 回答
0

你提到你string从另一个系统中得到一个你必须转换成Boolean类型的。因此,我将为此编写自己的转换器,而不是使用枚举:

public static class SpecificBooleanConverter
{
    private static Dictionary<string, bool> _AllowedValues;

    static SpecificBooleanConverter()
    {
        _AllowedValues = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
        _AllowedValues.Add("true", true);
        _AllowedValues.Add("false", false);
        _AllowedValues.Add("foo", true);
        _AllowedValues.Add("bar", false);
    }

    public static bool TryParse(string value, out bool result)
    {
        return _AllowedValues.TryGetValue(value, out result);
    }
}

然后可以这样调用:

bool dotNetBoolean;
var booleansFromOtherSystem = new[] { "hello", "TRUE", "FalSE", "FoO", "bAr" };

foreach (var value in booleansFromOtherSystem)
{
    if (!SpecificBooleanConverter.TryParse(value, out dotNetBoolean))
    {
        Console.WriteLine("Could not parse \"" + booleansFromOtherSystem + "\".");
    }

    if (dotNetBoolean == true)
    {
        Console.WriteLine("Yes, we can.");
    }
    else
    {
        Console.WriteLine("No, you don't.");
    }
}
于 2013-04-02T13:28:45.223 回答