What's the best way of using a pair (triple, etc) of values as one value in C#?

前端 未结 16 2275
时光说笑
时光说笑 2021-02-07 03:00

That is, I\'d like to have a tuple of values.

The use case on my mind:

Dictionary, object>

or

<         


        
16条回答
  •  梦如初夏
    2021-02-07 03:36

    You can relatively easily create your own tuple classes, the only thing that potentially gets messy is your equality and hashcode overrides (essential if you're going to use them in dictionaries).

    It should be noted that .Net's own KeyValuePair struct has relatively slow equality and hashcode methods.

    Assuming that isn't a concern for you there is still the problem that the code ends up being hard to figure out:

    public Tuple GetSomething() 
    {
        //do stuff to get your multi-value return
    }
    
    //then call it:
    var retVal = GetSomething();
    
    //problem is what does this mean?
    retVal.Item1 / retVal.Item3; 
    //what are item 1 and 3?
    

    In most of these cases I find it easier to create a specific record class (at least until C#4 makes this compiler-magic)

    class CustomRetVal {
        int CurrentIndex { get; set; }
        string Message { get; set; }
        int CurrentTotal { get; set; }
    }
    
    var retVal = GetSomething();
    
    //get % progress
    retVal.CurrentIndex / retVal.CurrentTotal;
    

提交回复
热议问题