C# TryParsing属性的用户输入
我似乎找不到答案的简单问题。本质上,这个对象的属性是一个C# TryParsing属性的用户输入,c#,object,attributes,console-application,user-input,C#,Object,Attributes,Console Application,User Input,我似乎找不到答案的简单问题。本质上,这个对象的属性是一个Char,我需要TryParse它来确保当用户输入一些东西时它不会抛出错误。我的老师没有教我们一个get和set(我想这就是它的名字?),所以我不得不用TryParse。我也有一个双精度和一个整数,但这不是重点。我知道我必须从这个开始,我试着这么做 employee1._gender = char.TryParse(InputUtilities.GetStringCharValue("Gender: "), out employee1._g
Char
,我需要TryParse
它来确保当用户输入一些东西时它不会抛出错误。我的老师没有教我们一个get
和set
(我想这就是它的名字?),所以我不得不用TryParse
。我也有一个双精度和一个整数,但这不是重点。我知道我必须从这个开始,我试着这么做
employee1._gender = char.TryParse(InputUtilities.GetStringCharValue("Gender: "), out employee1._gender);
它抛出了一个布尔错误,这让我很困惑。我是新来的,所以如果这是一个愚蠢的问题,我道歉。谢谢大家的帮助
employee1._gender = InputUtilities.GetStringCharValue("Gender: ");
很接近,您只是混淆了TryParse返回的错误代码和out参数,后者将是函数调用的目标。这是一个快速示例,请注意,提供的任何字符都将被视为有效字符(即Q):
一旦您了解了类的getter和setter,就可以重构代码以将所有逻辑放在那里,这就是OOP中封装的美妙之处 employee1中的性别数据类型是什么?
它抛出一个布尔错误
TryParse
返回一个bool
类型,指示解析是否成功\u性别
最有可能是char
类型,而不是bool
,类型不匹配。另外此对象的属性是一个字符
,您是指字段
<代码>属性有不同的含义。很可能,我道歉_性别是一个字符数据类型,是的,它是一个字段,我很抱歉混淆了这两者。回到这个答案,我甚至不敢相信我问了这个问题哈哈。谢谢你的帮助,不客气:-)如果你现在好了,接受答案,拿到票。
static void Main(string[] args)
{
Employee employee1 = new Employee();
Console.Write("Gender: ");
String userInput = Console.ReadLine();
if (char.TryParse(userInput, out employee1.gender))
Console.WriteLine("Ok, you specified: " + employee1.gender);
else
Console.WriteLine("Not valid character: " + userInput);
employee1.Print();
}
public class Employee {
public char gender = '?';
public void Print() {
Console.WriteLine("Gender is = " + gender);
}
}