0

我在理解 C# 方法的语法时遇到问题 - 特别是"must return something"错误。

我有这个方法:

public static class Connection
{
    public static List<string> getClients()
    {   
        List<string> clients = new List<string>();
        return clients;
    }
}

该方法不正确,因为我得到invalid expression term "return"了 ,所以我不完全知道该怎么做。有人可以解释一下这个公共空白等是如何工作的吗?

另外,为什么我不能执行以下操作?

public getClients()
    {   
        List<string> clients = new List<string>();
        return clients;
    }

我收到一条错误消息method must have a return type

4

4 回答 4

5

Every method needs to have a return type, or be declared with a void return type.

If you don't want to return anything, you would have a void return type, like below...

public void printSomething(string something)
{
  System.out.println(something);
}

If you want to return something, you have to declare the return type, like below...

public string returnSomething()
{
  string something = "something";
  return something;
}

So for your example, if you are returning "clients" which is of type List<string>, then you need to declare that return type, like below...

public List<string> getClients()
{
  List<string> clients = new List<string>();
  return clients;
}
于 2013-07-22T19:41:02.857 回答
2

What you're working with are called return types. When you define a method, you can set a type (such as integer, Bitmap, string, or even a custom class) to be returned as a value. That way, you can do the following:

int number = Average();

For a method that does not return a value, you can set the void keyword to signify that this method performs actions, but does not get a tangible result. Whereas the Average() method above returns an int when it's finished, a void returns nothing.

Additionally, public and static are keywords are adjectives that describe your method, be it void or not. Public refers to its privacy (or what sections of code can use it) and static refers to the lifetime and reference of a method.

于 2013-07-22T19:42:41.440 回答
1

method must have a return type在第二个代码中收到错误消息,因为您没有返回列表,但方法签名中不存在返回类型。对于没有返回类型的方法,您应该使用void.

public void method()//void or no return type
{
   //do something
}

您的第一个代码绝对没问题,应该可以正常工作

于 2013-07-22T19:46:21.200 回答
1

第一段代码应该可以工作。

如果您不想从函数返回任何内容,请使其返回 void:

public void DoWork() {
    int i = 1 + 1;
} // Don't return anything.
于 2013-07-22T19:38:20.460 回答