Is it possible for a function to return two values?

后端 未结 13 1570
谎友^
谎友^ 2020-12-31 08:41

Is it possible for a function to return two values? Array is possible if the two values are both the same type, but how do you return two different type values?

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 09:25

    Can a function return 2 separate values? No, a function in C# can only return a single value.

    It is possible though to use other concepts to return 2 values. The first that comes to mind is using a wrapping type such as a Tuple.

    Tuple GetValues() {
      return Tuple.Create(42,"foo");
    }
    

    The Tuple type is only available in 4.0 and higher. If you are using an earlier version of the framework you can either create your own type or use KeyValuePair.

    KeyValuePair GetValues() {
      return new KeyValuePair(42,"foo");
    }
    

    Another method is to use an out parameter (I would highly recomend the tuple approach though).

    int GetValues(out string param1) {
      param1 = "foo";
      return 42;
    }
    

提交回复
热议问题