C# 返回一个 enum 和一个 int 数组
我正在做一些需要返回枚举和整数数组的事情。我可以解决整个问题并使用 int 而不是枚举并将其添加为数组的第一个元素,但枚举确实有助于我的代码易读性。有什么办法可以同时返回两者吗?
I'm working on something where I would need to return an enum and an array of ints. 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. Is there any way to return both at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对此有 3 种常见的解决方案。
哪一个合适取决于具体情况和您的个人偏好:
对其中之一使用
out
参数。这不需要任何新类型,但调用不方便。此外,它可能无法在语义上捕获返回值之间的关系。使用
元组<,>
类型(.NET 4.0)。这只需要从现有的 BCL 类型构造一个封闭的泛型类型,但调用者可能不喜欢封装的属性具有无意义的名称:Item1
和Item2
还可以使用KeyValuePair<,>
类型或编写您自己的Pair<,>
类型来实现类似的目的。编写一个封装类,封装int数组和enum。更多工作,但对于调用者来说是最好的工作。
There are 3 common solutions to this.
Which one is appropriate would depend on the specific situation and your personal preference:
Use an
out
parameter for one of them. This doesn't require any new types, but is inconvenient to call. Additionally, it may not semantically capture the relationship between the returned values.Use the
Tuple<,>
type (.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
andItem2
You can also theKeyValuePair<,>
type or write your ownPair<,>
type to serve a similar purpose.Write a wrapper class that encapsulates the int array and the enum. More work, but nicest to work with for the caller.