Convert.ToBoolean 및 Boolean.Parse는 0과 1을 허용하지 않습니다.
부울을 구문 분석 할 때 0/1이 허용되지 않는 이유는 무엇입니까?
정수 유형 값을 구문 분석 할 때 구문 분석 할 숫자 문자열을 허용합니다. (그리고 만약 .NET이 "1 억 2 백 육십 오팔 백 육십 오"문자열을 파싱 할 수 있다면 나는 놀랄 것입니다).
부울을 특별하게 만드는 것은 무엇입니까? 내 경험상 그들은 본질적으로 0이 거짓이고 0이 아닙니다.
이와 같은 문자열을 구문 분석하는 bcl 메소드가 있습니까? 그렇지 않다면 그 이유는 무엇입니까?
참고 : 문자열 "0"과 "1"을 지정하는 것을 잊었습니다. 이미 int이면 예상대로 작동한다는 것이 궁금합니다. 아마도 이것이 혼란을 야기했을 것입니다.
0과 (0이 아님)은 "false"및 "true"와 같지 않으며 C에서 선택한 표현 일뿐입니다. 다른 언어에서는 true에 대해 0을 사용하고 false에 대해 -1을 사용하거나 다른 체계를 완전히 사용합니다. 부울은 0 또는 1 이 아니며 참 또는 거짓입니다.
또한 "예"와 "아니오", "끄기"및 "켜기"및 부울과 유사한 무수한 다른 모든 것을 처리해야합니까? 어디에 선을 그리겠습니까?
부울을 특별하게 만드는 것은 무엇입니까? 내 경험상 그들은 본질적으로 0이 거짓이고 0이 아닙니다.
이것은 구현 세부 사항이며 전혀 관련이 없습니다.
true
부울 값입니다. false
부울 값입니다. 다른 것은 없습니다.
문자열 "0"이 평가 false
되는 동안 다른 항목이 평가 되도록 구문 분석 true
하려면 다음을 사용할 수 있습니다.
!mystr.Equals("0");
FormatHelper
아래에 표시된 공유 클래스는라는 오버로드 된 메서드의 두 가지 변형을 사용하는 간단한 솔루션을 제공합니다 StringToBoolean
.
FormatHelper.StringToBoolean(String value)
FormatHelper.StringToBoolean(String value, Boolean NullOrEmptyDefault)
두 변형 모두 대소 문자를 구분하지 않는 문자열 일치를 제공합니다.
1) 문자열에서 부울로의 정상적인 변환은 비어 있거나 null 문자열을 false
다음 예는 boolean
값이 false
:-
Boolean myBool = FormatHelper.StringToBoolean("");
Boolean myBool = FormatHelper.StringToBoolean("0");
Boolean myBool = FormatHelper.StringToBoolean("false");
Boolean myBool = FormatHelper.StringToBoolean("False");
Boolean myBool = FormatHelper.StringToBoolean("no");
Boolean myBool = FormatHelper.StringToBoolean("off");
다른 모든 문자열 값은 다음과 같은 Boolean
값이 true
됩니다.
Boolean myBool = FormatHelper.StringToBoolean("1");
Boolean myBool = FormatHelper.StringToBoolean("true");
Boolean myBool = FormatHelper.StringToBoolean("True");
Boolean myBool = FormatHelper.StringToBoolean("yes");
Boolean myBool = FormatHelper.StringToBoolean("xyz blah");
참고 : BooleanStringOff
false / off에 대해 더 많은 (또는 더 적은) 값을 포함하도록 아래 클래스 의 값을 편집하십시오.
2) 위의 1)과 동일한 규칙을 따르지만 true
변환의 두 번째 인수로 기본값 을 제공 할 수 있습니다.
String
값이 비어 있거나 이면 기본값이 사용됩니다 null
. 누락 된 문자열 값이 true
상태 를 나타내야하는 경우 유용합니다 .
다음 코드 예제는 true
Boolean myBool = FormatHelper.StringToBoolean("",true);
다음 코드 예제는 false
Boolean myBool = FormatHelper.StringToBoolean("false",true);
이것은 FormatHelper
수업 코드입니다.
public class FormatHelper
{
public static Boolean StringToBoolean(String str)
{
return StringToBoolean(str, false);
}
public static Boolean StringToBoolean(String str, Boolean bDefault)
{
String[] BooleanStringOff = { "0", "off", "no" };
if (String.IsNullOrEmpty(str))
return bDefault;
else if(BooleanStringOff.Contains(str,StringComparer.InvariantCultureIgnoreCase))
return false;
Boolean result;
if (!Boolean.TryParse(str, out result))
result = true;
return result;
}
}
불행히도 이것은 .NET에서 많이 발생합니다. 예를 들어 XML Serializer인지 XmlConvert인지 기억할 수 없지만 True / False 대 / 소문자가 올바르지 않으면 그중 하나가 실패합니다.
정수를 통해 왕복하여 원하는 것을 얻을 수 있습니다.
string s = "2";
int i = Convert.ToInt32(s);
bool b = Convert.ToBoolean(i);
위의 경우 0이 아닌 것은 모두 참으로 평가됩니다.
For this reason, I created a class I use all over called ConversionStrategy which takes into account the source type and destination type and chooses the most ideal (and flexible) conversion strategy for making the conversion.
You want Convert.ToBoolean(int value)
not sure what's up with the Parse methods :-)
Code for no useful purpose:
int falseInt = 0;
int trueInt = 1;
bool falseBool;
bool trueBool;
if (bool.TryParse(falseInt.ToString(), out falseBool))
{
if (!falseBool)
{
MessageBox.Show("TryParse: False");
}
}
if (bool.TryParse(trueInt.ToString(), out trueBool))
{
if (!trueBool)
{
MessageBox.Show("TryParse: True");
}
}
falseBool = Convert.ToBoolean(falseInt);
trueBool = Convert.ToBoolean(trueInt);
if (!falseBool)
{
MessageBox.Show("Convert: False");
}
if (trueBool)
{
MessageBox.Show("Convert: True");
}
How about this?
byte i = 1; //or 0
bool myBool = BitConverter.ToBoolean(new byte[] { i }, 0)
To answer the question would be hard. Maybe because the narrow minded developers at Microsoft had their own reasons? No disrespect intended to them. Just saying they did not think about what it would need to be used for or how it would be used. I can't think of a reason why my extension below would not work for anyone. I mean a Boolean value is either on or off, true or false. In my mind it's basically binary. Parse methods for Int, Double, Char, Long, Byte, etc are more forgiving with their Parse methods.
However, consider this; You are looking to see if a value exists in an object. The same might be said for the following...
string myvar = "empty"; //Or maybe = "NULL"
if (String.IsNullOrEmpty(myvar))
{
//Should this be true?
}
Anyway, let's just make this simple. Here is my solution using an extension method to create a ToBoolean()
method for a string.
using System.Linq;
public static bool ToBoolean(this string input)
{
//Define the false keywords
String[] bFalse = { "false", "0", "off", "no" };
//Return false for any of the false keywords or an empty/null value
if (String.IsNullOrEmpty(input) || bFalse.Contains(input.ToLower()))
return false;
//Return true for anything not false
return true;
}
참고URL : https://stackoverflow.com/questions/1903776/convert-toboolean-and-boolean-parse-dont-accept-0-and-1
'Program Tip' 카테고리의 다른 글
8 개의 논리적 참 / 거짓 값을 1 바이트 안에 저장합니까? (0) | 2020.11.17 |
---|---|
GNU C 매크로 envSet (name)에서 (void) ""이름은 무엇을 의미합니까? (0) | 2020.11.17 |
django의 auth_user.username이 varchar (75)가 될 수 있습니까? (0) | 2020.11.17 |
Rails 3 : 새 중첩 리소스를 만드는 방법은 무엇입니까? (0) | 2020.11.17 |
Python 패키지 내부에서 (정적) 파일을 읽는 방법은 무엇입니까? (0) | 2020.11.17 |