简体   繁体   中英

return more than one output on c#

如何在c#函数中返回多个类型,就像我想返回字符串和数据表一样?

The simplest answer is to use the DataTable's TableName property.

The more general answer is to use a Tuple<DataTable, string> or write a class or struct.

use ref or out parameters

ref parameter : requires initilization by the caller method.

public string ReturnName(ref int position)
{
     position = 1;
     return "Temp"
}


public string GetName()
{
     int i =0;
     string name = ReturnName(ref i);
     // you will get name as Temp and i =1

}


// best use out parameter is the TryGetXXX patternn in various places like (int.TryParse,DateTime.TryParse)
 int i ;
 bool isValid = int.TryParse("123s",out i);

Use an out parameter:

public string Function(out DataTable result)

Call it like this:

DataTable table;
string result = Function(out table);

You can define your own class to use as the return type:

class MyReturnType
{
  public string String { get; set; }

  public DataTable Table { get; set; }
}

and return an instance of that. You could use a Tuple but it's often better to have meaningful type and property names, especially if someone else is going to be working on the software.

Or you could use an out parameter on the function.

The way you go depends on what is suitable for your situation. If the string and the DataTable are two parts of the same thing a class makes sense. If the string is for an error message when creating the DataTable fails an out parameter might be more appropriate.

使用元组作为回报。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM