首页 > 解决方案 > 类中的 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();

        }
    }
}

提前致谢!

标签: c#.net

解决方案


拿着这个:

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()您碰巧拥有的任何项目来工作。


推荐阅读