开发者

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. 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?


There are 3 common solutions to this. Which one is appropriate would depend on the specific situation and your personal preference:

  1. 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.

    public int[] MyMethod(out MyEnumType myEnum)
    { 
        myEnum = ...
        int[] nums = ...    
        return nums;
    }
    
  2. 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 and Item2 You can also the KeyValuePair<,> type or write your own Pair<,> type to serve a similar purpose.

    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. 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;
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜