c# - 我不明白 C# 中的字符串
问题描述
作为只使用过c++的人,我很困惑。我已经阅读了不同的解释,但我似乎仍然无法理解。例如,为什么我需要检查一个字符串是否是一个字符串?(tryparse 方法)如果它显然是一个数字,它是一个 int ......对吗?因此,例如,我当前的代码在一个函数中获取年龄并将其输出到主函数中。我尝试将其转换为 int,但出现错误 cs0019: Operator '==' cannot be applied to operands of 'int' and 'string'
public static string GetAge()
{
Console.WriteLine("\nPlease input age > ");
int age = Int32.Parse(Console.ReadLine());
if (age == "")
{
do {
Console.Write("Invalid input. Please try again > ");
age = Console.ReadLine();
} while ( age == "");
}
return age;
}
static void Main (){
Console.WriteLine("\nPlease note\nThis program is only applicable for users born between 1999 and 2010");
string name = GetName();
string year = GetYear();
int age = GetAge();
然后我也收到此错误 cs0029:无法将类型“int”隐式转换为“字符串”(第 49 行是返回年龄)和错误 cs0029:无法将第 58 行的类型“字符串”隐式转换为“int”(int age =获取年龄();)
解决方案
int.Parse
如果失败会抛出异常。我会将您的循环修改为:
int age;
while (!int.TryParse(Console.ReadLine(), out age))
Console.Write("Invalid input. Please try again > ");
return age;
int.TryParse
成功后将返回true
。
还要更改方法定义以返回一个int
:
public static int GetAge()
推荐阅读
- javascript - 如何在开始和结束时自定义 xAxis 标签?
- python - /post/ 处的 NoReverseMatch
- r - 每次在 R 中“重新出现”时,增加组的行号
- javascript - 在 TypeScript 中导入时出现“Uncaught SyntaxError: Unexpected token {”
- inheritance - 没有方法的子接口
- java - 为什么使用相同的时区获得不同的 localDate
- ruby-on-rails - 如何在 ruby 的 link_to 中添加 tabindex
- mobile - 通过移动应用更改 Google 表格时,“编辑”触发器未激活
- iis - 如何在 IIS 上发布 Polymer 2/3 项目?
- bash - 为什么 bash(来自 git 安装)突然给我分段错误?