为了整洁,我想知道,是否有可能将Y或N投入布尔?像这样的东西;
bool theanswer = Convert.ToBoolean(input);
长版;
bool theanswer = false;
switch (input)
{
case "y": theanswer = true; break;
case "n": theanswer = false; break
}
答案 0 :(得分:42)
不,没有内置的东西。
但是,如果你想默认为false,你可以使用:
bool theAnswer = (input == "y");
(包围就是为了清晰起见。)
考虑到问题文本与您获得的代码之间的差异,您可能需要考虑使其不区分大小写。一种方法:
bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
请注意,使用指定的字符串比较可以避免创建新字符串,这意味着您无需担心文化问题......除非您希望执行文化敏感的比较,课程。另请注意,我已将文字作为方法调用的“目标”,以避免在NullReferenceException
为input
时抛出null
。
答案 1 :(得分:8)
bool theanswer = input.ToLower() == "y";
答案 2 :(得分:5)
为字符串创建一个扩展方法,它执行类似于您在第二个算法中指定的内容,从而清理代码:
public static bool ToBool(this string input)
{
// input will never be null, as you cannot call a method on a null object
if (input.Equals("y", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (input.Equals("n", StringComparison.OrdinalIgnoreCase))
{
return false;
}
else
{
throw new Exception("The data is not in the correct format.");
}
}
并调用代码:
if (aString.ToBool())
{
// do something
}
答案 3 :(得分:5)
正如乔恩所建议的那样,没有像这样内置的东西。 John发布的答案为您提供了正确的方法。只是为了进一步澄清,您可以访问:
http://msdn.microsoft.com/en-us/library/86hw82a3.aspx link text
答案 4 :(得分:4)
怎么样。
bool theanswer = input.Equals("Y", StringComparison.OrdinalIgnoreCase);
或更安全的版本。
bool theanswer = "Y".Equals(input, StringComparison.OrdinalIgnoreCase);
答案 5 :(得分:0)
还是这个?
bool CastToBoolean(string input)
{
return input.Equals("Y", StringComparison.OrdinalIgnoreCase);
}
答案 6 :(得分:0)
我遇到了同样的问题,但解决了其他问题。
bool b=true;
decimal dec;
string CurLine = "";
CurLine = sr.ReadLine();
string[] splitArray = CurLine.Split(new Char[] { '=' });
splitArray[1] = splitArray[1].Trim();
if (splitArray[1].Equals("Y") || splitArray[1].Equals("y")) b = true; else b = false;
CurChADetails.DesignedProfileRawDataDsty1.Commen.IsPad = b;
答案 7 :(得分:0)
DotNetPerls有一个方便的类来解析各种字符串bool。
/// <summary>
/// Parse strings into true or false bools using relaxed parsing rules
/// </summary>
public static class BoolParser
{
/// <summary>
/// Get the boolean value for this string
/// </summary>
public static bool GetValue(string value)
{
return IsTrue(value);
}
/// <summary>
/// Determine whether the string is not True
/// </summary>
public static bool IsFalse(string value)
{
return !IsTrue(value);
}
/// <summary>
/// Determine whether the string is equal to True
/// </summary>
public static bool IsTrue(string value)
{
try
{
// 1
// Avoid exceptions
if (value == null)
{
return false;
}
// 2
// Remove whitespace from string
value = value.Trim();
// 3
// Lowercase the string
value = value.ToLower();
// 4
// Check for word true
if (value == "true")
{
return true;
}
// 5
// Check for letter true
if (value == "t")
{
return true;
}
// 6
// Check for one
if (value == "1")
{
return true;
}
// 7
// Check for word yes
if (value == "yes")
{
return true;
}
// 8
// Check for letter yes
if (value == "y")
{
return true;
}
// 9
// It is false
return false;
}
catch
{
return false;
}
}
}
被召唤;
BoolParser.GetValue("true")
BoolParser.GetValue("1")
BoolParser.GetValue("0")
可以通过添加参数重载来接受对象来进一步改进。
答案 8 :(得分:0)
Wonea gave an "IsTrue" source example from DotNetPerls.以下是它的两个较短版本:
.dat
OR:
public static bool IsTrue(string value)
{
// Avoid exceptions
if (value == null)
return false;
// Remove whitespace from string and lowercase it.
value = value.Trim().ToLower();
return value == "true"
|| value == "t"
|| value == "1"
|| value == "yes"
|| value == "y";
}
哎呀,如果你想得到真正的简短(和丑陋),你可以将其折叠成两行,如下所示:
private static readonly IReadOnlyCollection<string> LOWER_TRUE_VALUES = new string[] { "true", "t", "1", "yes", "y" };
public static bool IsTrue(string value)
{
return value != null
? LOWER_TRUE_VALUES.Contains(value.Trim().ToLower())
: false;
}
答案 9 :(得分:-1)
class Program
{
void StringInput(string str)
{
string[] st1 = str.Split(' ');
if (st1 != null)
{
string a = str.Substring(0, 1);
string b=str.Substring(str.Length-1,1);
if(
a=="^" && b=="^"
|| a=="{" && b=="}"
|| a=="[" && b=="]"
||a=="<" && b==">"
||a=="(" && b==")"
)
{
Console.Write("ok Formate correct");
}
else
{
Console.Write("Sorry incorrect formate...");
}
}
}
static void Main(string[] args)
{
ubaid: ;
Program one = new Program();
Console.Write("For exit Press N ");
Console.Write("\n");
Console.Write("Enter your value...=");
string ub = Console.ReadLine();
if (ub == "Y" || ub=="y" || ub=="N" || ub=="n" )
{
Console.Write("Are your want to Exit Y/N: ");
string ui = Console.ReadLine();
if (ui == "Y" || ui=="y")
{
return;
}
else
{
goto ubaid;
}
}
one.StringInput(ub);
Console.ReadLine();
goto ubaid;
}
}