简体   繁体   English

C#返回枚举和int数组

[英]C# Returning an enum and an int array

I'm working on something where I would need to return an enum and an array of ints. 我正在做一些我需要返回枚举和一系列int的东西。 I can go around the whole issue and use an int instead of the enum and add it as the first element of the array, but the enum really helps my code legibility. 我可以绕过整个问题并使用int而不是枚举并将其添加为数组的第一个元素,但枚举确实有助于我的代码易读性。 Is there any way to return both at the same time? 有没有办法同时返回两个?

There are 3 common solutions to this. 有3种常见的解决方案。 Which one is appropriate would depend on the specific situation and your personal preference: 哪一个适合取决于具体情况和您的个人偏好:

  1. Use an out parameter for one of them. 其中一个使用out参数。 This doesn't require any new types, but is inconvenient to call. 这不需要任何新类型,但是不方便打电话。 Additionally, it may not semantically capture the relationship between the returned values. 此外,它可能不会在语义上捕获返回值之间的关系。

     public int[] MyMethod(out MyEnumType myEnum) { myEnum = ... int[] nums = ... return nums; } 
  2. Use the Tuple<,> type (.NET 4.0). 使用Tuple<,>类型(.NET 4.0)。 This only requires the construction of a closed generic-type from an existing BCL type, but callers may not like the fact that the encapsulated properties have meaningless names: Item1 and Item2 You can also the KeyValuePair<,> type or write your own Pair<,> type to serve a similar purpose. 这只需要从现有的BCL类型构造一个封闭的泛型类型,但是调用者可能不喜欢封装的属性具有无意义的名称这一事实: Item1Item2您还可以使用KeyValuePair<,>类型或编写自己的Pair<,>类型以达到类似目的。

     public Tuple<int[], MyEnumType> MyMethod() { int[] nums = ... MyEnumType myEnum = ... return Tuple.Create(nums, myEnum); } 
  3. Write a wrapper class that encapsulates the int array and the enum. 编写一个封装int数组和枚举的包装类。 More work, but nicest to work with for the caller. 更多的工作,但最好与呼叫者一起工作。

     public class Wrapper { public int[] Nums { get { ... } } public MyEnumType MyEnum { get { ... } } } ... public Wrapper MyMethod() { Wrapper wrapper = ... return wrapper; } 

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

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