c# - 类中的 C# 无效令牌“int”
问题描述
从一本书中学习 C# 并刚刚陷入这个问题:类、结构或接口成员声明中的无效标记 'int'。我试图从一个方法返回一个数组。
using System;
using System.Collections.Generic;
namespace AdvanceMethodConcepts
{
class Program
{
public static void firstElementPrint(int[] a)
{
Console.WriteLine("The first element is {0}. \n", a[0]);
}
public static void printFirstListElement (List<int> a)
{
Console.WriteLine("The first list element is {0}\n", a[0]);
}
//this next line has the problem
public static void int[] ReturnUserInput()
{
int[] a = new int[3];
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine("Enter an integer ");
a[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Integer added to array.\n");
return a;
}
}
static void Main(string[] args)
{
int[] myArray = { 11, 2, 3, 4, 5 };
firstElementPrint(myArray);
List<int> myList = new List<int> { 1, 2, 3 };
printFirstListElement(myList);
int[] myArray2 = ReturnUserInput();
}
}
}
提前致谢!
解决方案
拿着这个:
public static void int[] ReturnUserInput()
并将其更改为:
public static int[] ReturnUserInput()
void
是返回类型。这意味着“这个函数不返回任何东西”。当您添加 时int[]
,您是在说“此函数不返回任何内容”并且还说“此函数返回一个整数数组”。这两件事相互矛盾,无论如何你只能使用一种返回类型。
当我在这里时,您需要将函数中的return
语句移到循环之后。你也可以减少这个:ReturnUserInput()
public static void firstElementPrint(int[] a)
{
Console.WriteLine("The first element is {0}. \n", a[0]);
}
public static void printFirstListElement (List<int> a)
{
Console.WriteLine("The first list element is {0}\n", a[0]);
}
仅此而已,您可以同时使用 anList<int>
和an调用int[]
:
public static void printFirstElement (IList<int> a)
{
Console.WriteLine("The first list element is {0}\n", a[0]);
}
或者这个,你可以用任何类型的列表或数组调用:
public static void printFirstElement<T>(IList<T> a)
{
Console.WriteLine("The first list element is {0}\n", a[0]);
}
它通过隐式调用ToString()
您碰巧拥有的任何项目来工作。
推荐阅读
- angular - 如何为迁移的域设置角度构建路径?
- javascript - 使用 AM 排序日期和时间 | jQuery中的PM
- amazon-web-services - 如何在 AWS 中为两个 CloudFront 设置 Canary Release?
- c# - 查找下一个日历年第 13 天的星期五
- julia - Julia 1.0 中的逗号任何类型的数字
- c# - Gmaps 异常:无法解析远程名称
- gcc - GDB 的下一条命令向后跳转到作用域末尾的所有堆栈分配对象
- javascript - 如何覆盖高阶组件的默认道具?
- php - 照片上传到服务器和数据库的问题
- ruby-on-rails - Rails 中的时区设置