C# 布尔值转换 bool转换
class Program
{
static void Main(string[] args)
{
Console.WriteLine("true: {0}", ToBoolean("true"));
Console.WriteLine("false: {0}", ToBoolean("false"));
Console.WriteLine("1: {0}", ToBoolean("1"));
Console.WriteLine("0: {0}", ToBoolean("0"));
Console.WriteLine("abcdefg: {0}", ToBoolean("abcdefg"));
bool? b = ToBoolean("abcdefg");
Console.Read();
}
/// <summary>
/// Converts a string to Boolean(bool)
/// </summary>
/// <param name="input">input data, e.g. 1->true</param>
/// <returns></returns>
public static bool? ToBoolean(string input)
{
bool result = false;
if (bool.TryParse(input, out result))
{
return bool.Parse(input);
}
if (input.Equals("1"))
{
return true;
}
else if (input.Equals("0"))
{
return false;
}
return null;
}
}