简体   繁体   English

在c#上返回多个输出

[英]return more than one output on c#

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

The simplest answer is to use the DataTable's TableName property. 最简单的答案是使用DataTable的TableName属性。

The more general answer is to use a Tuple<DataTable, string> or write a class or struct. 更一般的答案是使用Tuple<DataTable, string>或编写类或结构。

use ref or out parameters 使用ref或out参数

ref parameter : requires initilization by the caller method. ref参数:需要通过调用方法进行初始化。

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: 使用out参数:

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. 或者您可以在函数上使用out参数。

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. 如果字符串和DataTable是同一个东西的两个部分,那么一个类是有意义的。 If the string is for an error message when creating the DataTable fails an out parameter might be more appropriate. 如果在创建DataTable时字符串用于错误消息,则out参数可能更合适。

使用元组作为回报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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