C# FormatException 0不是布尔值的有效值

C# FormatException 0不是布尔值的有效值,c#,.net,C#,.net,我得到一个formatexception,代码如下。任何人都知道如何使BooleanConverter从0/1转换为true/false bool bVal=true; string sVal = "0"; Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal)); 谢谢你的帮助 只有两种情况,因此可以直接检查它们。只有两种情况,因此可以直接检查它们。尝试以下方法 public static bool C

我得到一个formatexception,代码如下。任何人都知道如何使BooleanConverter从0/1转换为true/false

 bool bVal=true;
 string sVal = "0";
 Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));

谢谢你的帮助

只有两种情况,因此可以直接检查它们。

只有两种情况,因此可以直接检查它们。

尝试以下方法

public static bool ConvertToBasedOnIntValue(string value) {
  // error checking omitted for brevity
  var i = Int32.Parse(value);
  return value == 0 ? false : true;
}

或者您可以使用不会抛出异常的下面的内容,但是它会认为所有不完全是0的事物都是真的

public static bool ConvertToBasedOnIntValue(string value) {
  if ( 0 == StringComparer.CompareOrdinal(value, "0") ) {
    return false;
  }
  return true;
}
试试下面的方法

public static bool ConvertToBasedOnIntValue(string value) {
  // error checking omitted for brevity
  var i = Int32.Parse(value);
  return value == 0 ? false : true;
}

或者您可以使用不会抛出异常的下面的内容,但是它会认为所有不完全是0的事物都是真的

public static bool ConvertToBasedOnIntValue(string value) {
  if ( 0 == StringComparer.CompareOrdinal(value, "0") ) {
    return false;
  }
  return true;
}

如果要使用Int32.Parse,请改用Int32.TryParse。如果转换失败,它不会抛出,而是返回true或false。这意味着如果你所做的只是检查你的输入是否是一个值,那么它的性能会更好。例如:

public static bool ConvertToBool(string value)
{
    int val = 0;
    return (int.TryParse(value, out val) && val == 0) ? false : true;
}
我对三元运算符(x?y:z)有一种过火的倾向,因此这里有一个稍微容易阅读的版本:

public static bool ConvertToBool(string value)
{
    int val = 0;
    if (int.TryParse(value, out val))
    {
        return val == 0 ? false : true;
    }

    return false;
}

(我对它们都进行了测试。“1”返回true,“0”返回false。)

如果要使用Int32.Parse,请改用Int32.TryParse。如果转换失败,它不会抛出,而是返回true或false。这意味着如果你所做的只是检查你的输入是否是一个值,那么它的性能会更好。例如:

public static bool ConvertToBool(string value)
{
    int val = 0;
    return (int.TryParse(value, out val) && val == 0) ? false : true;
}
我对三元运算符(x?y:z)有一种过火的倾向,因此这里有一个稍微容易阅读的版本:

public static bool ConvertToBool(string value)
{
    int val = 0;
    if (int.TryParse(value, out val))
    {
        return val == 0 ? false : true;
    }

    return false;
}

(我对它们都进行了测试。“1”返回true,“0”返回false。)

我刚刚构建了一个帮助函数,它将处理布尔函数的特殊情况:

    Private Shared Function StringConverter(ByVal colValue As String, ByVal propertyType As Type) As Object

    Dim returnValue As Object

    'Convert the string value to the correct type
    Select Case propertyType
        Case GetType(Boolean)
            'Booleans need to be coded separately because by default only "True" and "False" will map to a Boolean
            'value. SQL Server will export XML with Booleans set to "0" and "1". We want to handle these without
            'changing the xml.
            Select Case colValue
                Case "0"
                    returnValue = False
                Case "1"
                    returnValue = True
                Case "False"
                    returnValue = False
                Case "True"
                    returnValue = True
                Case Else
                    Throw New ArgumentException("Value of '" & colValue & "' cannot be converted to type Boolean.")
            End Select
        Case Else
            'Let .Net Framework handle the conversion for us
            returnValue = TypeDescriptor.GetConverter(propertyType).ConvertFromString(colValue)

    End Select

    Return returnValue

End Function

我刚刚构建了一个helper函数来处理布尔函数的特殊情况:

    Private Shared Function StringConverter(ByVal colValue As String, ByVal propertyType As Type) As Object

    Dim returnValue As Object

    'Convert the string value to the correct type
    Select Case propertyType
        Case GetType(Boolean)
            'Booleans need to be coded separately because by default only "True" and "False" will map to a Boolean
            'value. SQL Server will export XML with Booleans set to "0" and "1". We want to handle these without
            'changing the xml.
            Select Case colValue
                Case "0"
                    returnValue = False
                Case "1"
                    returnValue = True
                Case "False"
                    returnValue = False
                Case "True"
                    returnValue = True
                Case Else
                    Throw New ArgumentException("Value of '" & colValue & "' cannot be converted to type Boolean.")
            End Select
        Case Else
            'Let .Net Framework handle the conversion for us
            returnValue = TypeDescriptor.GetConverter(propertyType).ConvertFromString(colValue)

    End Select

    Return returnValue

End Function

您的原始代码足够好,只是无法将字符串值设置为“0”和“1”。在您的代码中,TypeConverter.ConvertFrom()最终将调用Boolean.TryParse(),其代码如下所示(感谢Reflector!)

因此,对您的代码进行以下更改,您应该会做得很好:

bool bVal = true;
string sVal = "false";
Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));

您的原始代码足够好,只是无法将字符串值设置为“0”和“1”。在您的代码中,TypeConverter.ConvertFrom()最终将调用Boolean.TryParse(),其代码如下所示(感谢Reflector!)

因此,对您的代码进行以下更改,您应该会做得很好:

bool bVal = true;
string sVal = "false";
Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));


我正在使用一个使用类型转换器转换字符串的库。。。因此,如果我对布尔字段传递0/1,就会得到这个异常。我无法控制它如何转换..你能提供更多关于你能控制什么的信息吗?您能确保字符串正确地为“false”和“true”吗?我会在内部将0s和1s转换为int或字符串(将0s和1s映射为int或字符串,不要尝试直接映射到Bool),然后添加一个在运行时转换为Bool的“get”属性,在代码中需要的位置返回所需的值。hmm。。这是个好主意。我将看看是否可以将它作为一个整数导入到我的表中,并像您所说的那样动态地将其转换为布尔值。再次感谢。我正在使用一个使用类型转换器转换字符串的库。。。因此,如果我对布尔字段传递0/1,就会得到这个异常。我无法控制它如何转换..你能提供更多关于你能控制什么的信息吗?您能确保字符串正确地为“false”和“true”吗?我会在内部将0s和1s转换为int或字符串(将0s和1s映射为int或字符串,不要尝试直接映射到Bool),然后添加一个在运行时转换为Bool的“get”属性,在代码中需要的位置返回所需的值。hmm。。这是个好主意。我将看看是否可以将它作为一个整数导入到我的表中,并像您所说的那样动态地将其转换为布尔值。再次感谢。我要建议的是,正如在C中一样,非零字符串映射为true。我正在使用linqtocsv库,在我的csv文件中,我有一个0和1的列。在我的描述中,该字段被标记为可为空的布尔值(bool?)。因此,当库将我的csv文件转换为数据库时,它会执行以下操作:field.TypeConverter.ConvertFromString(value)。这里的值是“0”或“1”,TypeConverter变成BooleanConverter,它抛出FormatException。谢谢你们两位的建议。我不确定我是否能在我的案例中实现这一点!我想说的是,正如在C中一样,非零字符串映射为true。我使用的是linqtocsv库,在我的csv文件中,有一列是0和1。在我的描述中,该字段被标记为可为空的布尔值(bool?)。因此,当库将我的csv文件转换为数据库时,它会执行以下操作:field.TypeConverter.ConvertFromString(value)。这里的值是“0”或“1”,TypeConverter变成BooleanConverter,它抛出FormatException。谢谢你们两位的建议。我不确定我是否能在我的案例中实现这一点!您的代码很好,只是字符串值不可转换。表示为字符串的布尔值总是解析为“真”或“假”…我不明白为什么要将0转换为布尔值,这看起来像是C/C++编程。使用0和1表示真/假,可能导致代码难以读取。您的代码很好,但字符串值不可转换。表示为字符串的布尔值总是解析为“真”或“假”…我不明白为什么要将0转换为布尔值,这看起来像是C/C++编程。使用0和1表示真/假,可能会导致难以阅读的代码。这是一篇相当古老的文章,但由于这是公认的答案,我认为有必要说三元运算符(例如,
val==0?false:true
)完全没有必要,并且使代码更难阅读。只需使用
val!=0
(第一个示例也可以从更改中受益)。这是一篇相当古老的帖子,但由于它是公认的答案,我认为有必要说三元运算符(例如,
val==0?false:true
)完全没有必要,并且使代码变得非常复杂