如何从c#中的方法返回多个值

如何从c#中的方法返回多个值

问题描述:

如何从c#中的方法返回多个值,其中一个是自定义类列表值,另一个是十进制。

How to return multiple value from method in c# where one is custom class list value and another is decimal.

有不同的方法可以做到这一点,但是所有方法分为3种方式;你也可以把它们组合起来。

There are different ways to do that, but all approaches are classified into 3 ways; and also you can combine them.


  1. 这个函数可以返回一个对象。
  2. 另外,可以使用 out 参数返回一个或多个对象。它也可以是 ref ,但是返回将不是强制性的,这可能是个问题。
  3. 返回一些提到的对象的方法上面可以用来返回一些复合对象。您可以使用表示要返回的多个对象的成员声明某些类型。因此,您可以在一个中返回多个组合对象。这种复合类型可以是您自己的,也可以是集合类之一。您还可以使用泛型类型 System.Collections.Generic.KeyValuePair 返回一对对象,或使用泛型类型 System.Tuple返回1-8个对象

    http://msdn.microsoft.com/en-us/library/5tbh8a42%28v=vs.110%29.aspx [ ^ ],

    http://msdn.microsoft.com/en-us/library/system.tuple%28v= vs.110%29.aspx [ ^ ]。

  1. One object can be returned as the result of the function.
  2. Additionally, one or more objects can be returned using out parameter. It also can be ref, but then return won't be mandatory, which could be a problem.
  3. Each of the ways to return some object mentioned above can be used to return some compound object. You can declare some type with the members representing more than one objects to be returned. So, you can return multiple objects composed in one. This compound type can be your own, or it could be one of collection classes. You can also return a pair of objects using the generic type System.Collections.Generic.KeyValuePair or 1-8 objects using the generic type System.Tuple:
    http://msdn.microsoft.com/en-us/library/5tbh8a42%28v=vs.110%29.aspx[^],
    http://msdn.microsoft.com/en-us/library/system.tuple%28v=vs.110%29.aspx[^].





-SA


C#方法的实际返回值只能是单个对象实例 - 例如一个类,一个列表或一个double - 但是有一些方法可以获得更多的值b确认调用方法。



首先,您可以将所需的值封装在自定义类中,该类只包含自定义类列表值和小数。

The actual return value of a C# method can only ever be a single object instance - a class, or a list, or a double for example - but there are ways to get more values back to the calling method.

First you can encapsulate the values you want in a custom class, which holds just the custom class list value and a decimal.
public class ReturnValue
   {
   public List<MyClass> List;
   public double Value;
   }

public ReturnValue MyMethod()
   {
   ReturnValue ret = new ReturnValue();
   ...
   return ret;
   }

这有点笨拙,但是有效。



然后你可以用 ref out 您方法的参数:

That's a little clumsy, but it works.

Then you can use ref and out parameters on your method:

public bool MyMethod(ref List<MyClass> list, out double d)
   {
   foreach(MyClass in list)
      {
      ...
      }
   list = new List<MyClass>();
   ...
   d = 1.23;
   return true;
   }

这可以更加灵活,但有时看起来有点粗糙。

This can be a lot more flexible, but looks a little rough and ready sometimes.


你可以返回

)包含两个属性(listvalue和decimal)的类的对象。

2)您可以返回 KeyValuePair [ ^ ]。

3)返回元组 [ ^ ]具有多个值。
You can return
1) An object of a class that contains two attributes ( listvalue and decimal).
2) You can return a KeyValuePair[^].
3) Return a Tuple[^] with multiple values.